Home > Mobile >  Can someone please explain me why can't return a smart pointer?
Can someone please explain me why can't return a smart pointer?

Time:09-25

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

CodePudding user response:

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.

  • Related