的unique_ptr 对于阵列专业化拉姆达定制删除[复制](unique_ptr la

2019-06-23 22:55发布

这个问题已经在这里有一个答案:

  • 如何使用一个定制删除与一个std ::的unique_ptr成员? 6个回答

最近,我开始移植我许多现有的C ++应用程序代码到C ++ 11,现在,我转换到新的智能指针的std ::的unique_ptrstd :: shared_ptr的 ,我对自定义删除器一个具体的问题。 我想补充一个lambda记录看到我删除被称为在那里,但我不能让数组专业化版本进行编译。 建议将是非常赞赏。

我已经白白被搜索用于阵列专业化的unique_ptr一个定制删除用于VC ++ 10GCC 4.5.2+的一个例子。 我想打印时,删除器被称为拉姆达日志消息 - 主要是为了确保所有,我认为会超出范围的指针都是这样做的。 这是可能的专业化的阵列版本? 我可以得到它与非数组版本的工作,我也可以得到它与一个数组专业化如果我通过一个外部结构“MyArrayDeleter”作为第二个参数的工作。 还有一两件事,将有可能去除难看的std ::功能我以为我可以让拉姆达签名找出答案。

struct MySimpleDeleter {
    void operator()(int* ptr) const {
        printf("Deleting int pointer!\n");
        delete ptr;
    }
};
struct MyArrayDeleter {
    void operator()(int* ptr) const {
        printf("Deleting Array[]!\n");
        delete [] ptr;
    }
};
{
    // example 1 - calls MySimpleDeleter where delete simple pointer is called
    std::unique_ptr<int, MySimpleDeleter> ptr1(new int(5));

    // example 2 - correctly calls MyArrayDeleter where delete[] is called
    std::unique_ptr<int[], MyArrayDeleter> ptr2(new int[5]);

    // example 3 - this works (but default_delete<int[]> would have been passed
    // even if I did not specialize it as it is the default second arg
    // I only show it here to highlight the problem I am trying to solve
    std::unique_ptr<int[], std::default_delete<int[]>> ptr2(new int[100]);

    // example 3 - this lambda is called correctly - I want to do this for arrays
    std::unique_ptr<int, std::function<void (int *)>> ptr3(
        new int(3), [&](int *ptr){ 
            delete ptr; std::cout << "delete int* called" << std::endl; 
        });

    // example 4 - I cannot get the following like to compile
    // PLEASE HELP HERE - I cannot get this to compile
    std::unique_ptr<int[], std::function<void (int *)>> ptr4(
        new int[4], [&](int *ptr){  
            delete []ptr; std::cout << "delete [] called" << std::endl; 
        });
}

The compiler error is as follows:

The error from the compiler (which complains about the new int[4] for ptr4 below is:
'std::unique_ptr<_Ty,_Dx>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty,_Dx>'
1>          with
1>          [
1>              _Ty=int [],
1>              _Dx=std::tr1::function<void (int *)>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory(2513) : see declaration of 'std::unique_ptr<_Ty,_Dx>::unique_ptr'
1>          with
1>          [
1>              _Ty=int [],
1>              _Dx=std::tr1::function<void (int *)>
1>          ]

Answer 1:

关于什么:

auto deleter=[&](int* ptr){...};
std::unique_ptr<int[], decltype(deleter)> ptr4(new int[4], deleter);


Answer 2:

First of first, I use VC2010 with SP1, Mingw g++ 4.7.1

For array new, unique_ptr already support it in a clean way:

struct X
{
    X()   { puts("ctor"); }
   ~X()   { puts("dtor"); }
};

unique_ptr<X[]>  xp(new X[3]);

The output is:

ctor
ctor
ctor
dtor
dtor
dtor

For customized deleter, unfortunately, it's inconsistent between VC2010 and g++:

VC2010:

  unique_ptr<FILE, function<void (FILE*)> > fp(fopen("tmp.txt", "w"), [](FILE *fp){
    puts("close file now");
    fclose(fp);
  });

g++:

  unique_ptr<FILE, void (*)(FILE*) > fp(fopen("tmp.txt", "w"), [](FILE *fp){
    puts("close file now");
    fclose(fp);
  });

The method by Managu is very well, because inline lambda is cool but hurt readability IMHO. It also emphsize that release resource before acquisition(RAII).

Here I suggest a declartive way to separate resource acquisition and release(Scope Guard, works for both VC2010 and g++ 4.7.1):

template<typename T>
struct ScopeGuard
{
    T deleter_;
    ScopeGuard( T deleter) : deleter_(deleter) {}
    ~ScopeGuard() { deleter_() ; }
};
#define UNI_NAME(name, line) name ## line
#define ON_OUT_OF_SCOPE_2(lambda_body, line) auto UNI_NAME(deleter_lambda_, line) = [&]() {    lambda_body; } ; \
       ScopeGuard<decltype(UNI_NAME(deleter_lambda_, line))> \
       UNI_NAME(scope_guard_, line)  ( UNI_NAME(deleter_lambda_, line ));
#define ON_OUT_OF_SCOPE(lambda_body) ON_OUT_OF_SCOPE_2(lambda_body, __LINE__)

FILE * fp = fopen("tmp.txt", "w");
ON_OUT_OF_SCOPE( { puts("close file now"); fclose(fp); } );

The point is you can get a resource in the old, clear way, and declare the statement to release the resource immediately following the resource-acquisition line.

The drawback is you cannot forward a single object around along with it's deleter.

For FILE *, shared_ptr can be used as an alternative pointer for the same purpose(maybe a little heavy-weight, but works well for both VC2010 and g++)

shared_ptr fp2 ( fopen("tmp.txt", "w"), [](FILE * fp) { fclose(fp); puts("close file"); } );



文章来源: unique_ptr lambda custom deleter for array specialization [duplicate]