简体   繁体   中英

Returning unique_ptr which is function parameter

I have the following method:

std::unique_ptr<Req> RequestConverter::SetReg(
    const std::unique_ptr<Req> pb_req, ...) {

I want to return parameter pb_req from the above method. I get this error (with or without std::move):

error: call to deleted constructor of 'std::unique_ptr<Req>'

What's recommended approach ?

Thanks

The unique_ptr copy constructor is marked as deleted, ie the following

unique_ptr(const unique_ptr&) = delete;

And when you return a const unique_ptr<Req> from your function, the return value is treated as an rvalue, and therefore the exact match for a constructor if available would be

unique_ptr(const unique_ptr&&);

The move constructor does not match const unique_ptr<Req>&& because it requires a non const rvalue reference. And so the closest match is the copy constructor which is deleted, therefore this does not work.

But the question you should be asking yourself is, why do you want to mark the unique_ptr to be const in the first place? A const unique_ptr means that the pointer is const, and not the pointed to thing. If you want a unique_ptr to const, you should do unique_ptr<const Req> instead.

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