0

I was wondering what could be wrong with returning a smart pointer. The compiler throws that the constructor itself has been deleted. So I tried with returning the reference and it works, why is this possible?

#include <iostream>
#include <memory>
using namespace std;

using unique_int = std::unique_ptr<int>;
unique_int p_Int = std::make_unique<int>();

unique_int GetPtr()
{
    return p_Int;
}

unique_int& GetPtrAddr()
{
    return p_Int;
}

The error message is

function "std::unique_ptr<_Ty, _Dx>::unique_ptr(const std::unique_ptr<_Ty, _Dx>&)[with _Ty=int, Dx=std::default_delete<int>]"(declared at line 3269 of "memory library path") cannot be referenced -- it is a deleted function
east1000
  • 1,240
  • 1
  • 10
  • 30
Game_dev
  • 27
  • 7

1 Answers1

3

Let's examine what would happen when you return a std::unique_ptr by value. unique_int function creates a temporary object of std::unique_ptr type, for which a copy-initialization of the temporary std::unique_ptr from p_int, which you return. But the whole point of std::unique_ptr, is that it cannot be copied, only moved.

Karen Baghdasaryan
  • 2,407
  • 6
  • 24
  • Thanks this explanation made me clear so basically unique_ptr can exist just one type of itself, but shared_ptr and weak_ptr can have two variables having the same address. – Game_dev Sep 24 '21 at 10:47
  • @Game_dev Yes, you understand correctly. – Karen Baghdasaryan Sep 24 '21 at 10:53
  • @Game_dev • if you need a smart pointer with value semantics, someone made a [`value_ptr`](https://buckaroo.pm/blog/value-ptr-the-missing-smart-ptr) for that purpose. – Eljay Sep 24 '21 at 12:01