0

For example

class A
{
public:
    setB(unique_ptr<B> b) {???;}
    setB(unique_ptr<B>& b) {???;}
    setB(unique_ptr<B>&& b) {???;}

private:
    unique_ptr<B> mB;
};

How to transfer or move (not copy) the arguments content's ownership to the class member?

4

1 回答 1

4

The first and third alternatives are basically equivalent in the particular case of std::unique_ptr, and better than the second alternative (which does not allow temporaries).

The first and third alternatives are equivalent in that from the caller point of view she needs an rvalue-reference to construct the argument to the first overload. Conceptually there is potentially an extra copy of std::unique_ptr but I doubt that will cause any real instruction in the binary and even if it did, it would be just a pointer copy and setting (2 cpu instructions)

于 2013-08-08T18:38:08.870 回答