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 ?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With