简体   繁体   中英

std::unique_ptr custom deleter

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

Constructor

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

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

Cause of error described here .

I decided since 'std::default_delete<_Ty>::operator () is private because child class ( std::unique_ptr in this case) has specified private inheritance that I would write my own custom deleter. Problem is I am too uncomfortable with the syntax and notation to succeed.

This line

error_(new ErrorHandling(fileService, writer));

is an error because unique_ptr doesn't have an operator() . The error message is a bit misleading, because its base class seems to have one (but luckily private).

You probably intended

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

which makes the unique_ptr own a new object.

The problem is that you're trying to use the function-call operator on a unique_ptr , which is not a valid thing to do. Then some confusion is caused because your particular implementation happens to have an inaccessible operator, rather than no operator at all, giving a weird error message.

I assume you're actually trying to reset error_ to own a new pointer:

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

UPDATE: if you do want a custom deleter (which, to reiterate, you don't in this situation), it might look like:

struct ErrorHandlingDeleter
{
    void operator()(ErrorHandling * p) {/* do something to release the pointer */}
};

std::unique_ptr<ErrorHandling, ErrorHandlingDeleter> error;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM