Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Return const unique_ptr

Tags:

c++

c++11

I am wondering why I get an error when compiling:

const std::unique_ptr<int> get() {      return std::make_unique<int>(10); }  int main() {       const std::unique_ptr<int> value = get();      return EXIT_SUCCESS; } 

I get the following error:

main.cpp: In function ‘int main()’: main.cpp:10:44: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’      const std::unique_ptr<int> value = get(); 

It compiles correctly when I remove const from the get signature.

Is there any way to return a constant unique_ptr ?

like image 933
jean553 Avatar asked Jul 24 '17 11:07

jean553


People also ask

What happens when you return a Unique_ptr?

If a function returns a std::unique_ptr<> , that means the caller takes ownership of the returned object. class Base { ... }; class Derived : public Base { ... }; // Foo takes ownership of |base|, and the caller takes ownership of the returned // object.

What is std :: Unique_ptr?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

Can Unique_ptr be moved?

A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.


1 Answers

Because the unique_ptr is constant it can not be moved only copied. And copying a unique_ptr is not allowed (otherwise it would not be "unique").

If the data pointed to by the pointer should be constant, then use std::unique_ptr<const int> instead.

like image 70
Some programmer dude Avatar answered Oct 12 '22 23:10

Some programmer dude