What is going on?
You cannot create a second instance of Test because this implies you need a copy of the unique_ptr, which is not possbile. A unique_ptr can only be moved. Try implementing a move asignment operator and move o
like so:
class Test
{
public:
Test() = default;
Test(Test&& other) noexcept
: ptr(std::move(other.ptr))
{
}
private:
std::unique_ptr<int> ptr = std::make_unique<int>(1);
};
int main()
{
Test o;
Test t = std::move(o);
}
If you want to copy the int underlying the unique_ptr, you need to define a custom copy constructor like this:
class Test
{
public:
Test() = default;
Test(const Test& other)
:
ptr(new int(*other.ptr))
{
}
Test(Test&& other) noexcept
: ptr(std::move(other.ptr))
{
}
private:
std::unique_ptr<int> ptr = std::make_unique<int>(1);
};
int main()
{
Test o;
Test t = o;
}
However, NOTE, that the pointers point to two DIFFERENT ints.
If you want shared ownership, you have to (and should) use shared_ptr like this:
class Test
{
private:
std::shared_ptr<int> ptr = std::make_shared<int>(1);
};
int main()
{
Test o;
Test t = o;
}