std :: unique_ptr自定义删除器

Mus*_*shy 0 c++ unique-ptr

参考嗯,std :: unique_ptr的自定义删除器是如何工作的?

构造函数

std::unique_ptr<ErrorHandling> error_;

RecursiveDescentParser::RecursiveDescentParser(std::string inputStream, bool fileService, 
            boost::optional<std::string> filePathName, std::ofstream &writer){

    if (fileService == true){
        error_(new ErrorHandling(fileService, writer));  <---- compiler error
    }
    else{
        error_(new ErrorHandling(fileService, std::ofstream())); <---- compiler error
    }       
}
Run Code Online (Sandbox Code Playgroud)

编译错误

Error   1   error C2247: 'std::default_delete<_Ty>::operator ()' not accessible because 'std::unique_ptr<_Ty>' uses 'private' to inherit from 'std::_Unique_ptr_base<_Ty,_Dx,_Empty_deleter>'
Run Code Online (Sandbox Code Playgroud)

这里描述的错误原因.

我之所以认为'std::default_delete<_Ty>::operator ()private因为子类(std::unique_ptr在这种情况下)指定private inheritance我会编写自己的自定义删除器.问题是我对语法和符号成功感到不舒服.

Bo *_*son 5

这条线

error_(new ErrorHandling(fileService, writer));
Run Code Online (Sandbox Code Playgroud)

是一个错误,因为unique_ptr没有operator().错误消息有点误导,因为它的基类似乎有一个(但幸运的是私有).

你可能打算

error_.reset(new ErrorHandling(fileService, writer));
Run Code Online (Sandbox Code Playgroud)

这使unique_ptr自己成为一个新的对象.