c++ - std::unique_ptr 自定义删除器

标签 c++ unique-ptr

引用 Well, how does the custom deleter of std::unique_ptr work?

构造函数

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
    }       
}

编译错误

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>'

错误原因描述here .

我决定自 'std::default_delete<_Ty>::operator ()private因为子类(在本例中为 std::unique_ptr)指定了 private inheritance我会写我自己的自定义删除器。问题是我对成功的语法和符号太不舒服了。

最佳答案

这一行

error_(new ErrorHandling(fileService, writer));

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

你可能有意

error_.reset(new ErrorHandling(fileService, writer));

这使得 unique_ptr 拥有一个新对象。

关于c++ - std::unique_ptr 自定义删除器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15884034/

相关文章:

c++ - 数组和引用传递

c++ - 字符串数组,我该如何使用它?执行

c++ - 如何最好地为 C++11 中的 unique_ptr 中的普通数组制作迭代器?

c++ - 使用 unique_ptr<T> 和前向声明会导致 C2027 和 C2338

c++ - 如何设置两个 vector<unique_ptr<...>> 彼此相等?

c++ - 使用递归函数对 XML 树进行预序遍历?

c++ - 动态数组 - 查找容量

c++ - 条件为假时执行的 if 语句

c++ - 为什么我们不能将 "="用于 shared_ptr 或 unique_ptr?

c++ - 通过 std::unique_ptr 使用 std::map 访问运算符 [] 的正确语法