I came across a weird problem. I get an error message in setGetDog() method when written this way:
class Dog
{
public:
void bark() { std::cout << "Bark!" << std::endl; }
};
class test
{
public:
std::unique_ptr<Dog> setGetDog()
{
if (!dog_)
{
dog_ = std::make_unique<Dog>();
}
return dog_;
}
private:
std::unique_ptr<Dog> dog_;
};
int main()
{
auto testClass = std::make_unique<test>();
auto dog = testClass->setGetDog();
}
Error is like this:
error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Dog; _Dp = std::default_delete<Dog>]'
But when I change the implementation to:
std::unique_ptr<Dog> setGetDog()
{
return std::make_unique<Dog>();
}
It works just fine.
What is the matter with dog_
?
I do not understand why the error states that it is deleted when in fact test
is still alive when the method was called (and so dog_
as well).
I know I can write this some other way but I'm specifically curious on why behavior is like this on this implementation.
Can anyone please enlighten me?