The following situations involve transferring ownership from one unique_ptr
to another: returning from a function, and passing as a parameter to a function like a constructor.
Say you have some polymorphic type Animal
:
struct Animal {
virtual ~Animal() {}
virtual void speak() = 0;
};
with concrete subclasses Cat
and Dog
:
struct Cat : Animal {
void speak() override { std::cout << "Meow!
"; }
};
struct Dog : Animal {
void speak() override { std::cout << "Woof!
"; }
};
And you want a simple factory that creates a pet based on a required value of obedience. Then the factory must return a pointer. We want the pet factory to transfer ownership of the created pet to the caller so a reasonable return type is std::unique_ptr<Animal>
:
std::unique_ptr<Animal> createPet(double obedience) {
if (obedience > 5.0)
return std::make_unique<Dog>();
return std::make_unique<Cat>();
}
Now, say we want to create a House
that will own the pet then we might want to pass the pet into the constructor of the House
. There is some debate (see comments on this blog post) about how best to pass a unique_ptr
to a constructor but it would look something like this:
class House {
private:
std::unique_ptr<Animal> pet_;
public:
House(std::unique_ptr<Animal> pet) : pet_(std::move(pet)) {}
};
We have passed the unique_ptr
into the constructor and have then "moved" it to the member variable.
The calling code could look something like:
auto pet = createPet(6.0);
House house(std::move(pet));
After constructing the House
, the pet
variable will be nullptr
because we have transferred ownership of the pet to the House
.
Live demo
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…