Consider the following code:
#include <memory>
class Object
{
public:
Object(int* _i) : i(std::unique_ptr<int>(_i)) {}
Object(Object&& other) : i(std::move(other.i)) {}
private:
std::unique_ptr<int> i;
};
class Holder
{
public:
Holder(Object&& _obj) : obj(std::make_unique<Object>(_obj)) {}
private:
std::unique_ptr<Object> obj;
};
int main()
{
Holder h(Object(new int(42)));
return 0;
}
The compiler complains about copies of an Object
instance being made, which would obviously be illegal since Object
has a unique_ptr
member. Does that error occur because I pass my parameter by-value
? Shouldn't the signature of my constructor of Holder
force a call by-reference
?
What I understand even less is that after changing the constructor of my Holder
class to
Holder(Object&& _obj) : obj(std::make_unique<Object>(std::move(_obj))) {}
the code compiles just fine. This does not make any sense to me, since if there was a copy made while passing the Object
into the constructor of Holder
changing anything within the constructor shouldn't resolve this.