Why does the interface for auto_ptr specify two copy-constructor-like constructors
I was going through the auto_ptr documentati开发者_StackOverflow社区on on this link auto_ptr There is something which i could not fully understand why is it done. In the interface section there are two declarations for its copy constructor
1)
auto_ptr(auto_ptr<X>&) throw ();
2)
template <class Y>
auto_ptr(auto_ptr<Y>&) throw();
What purpose is this for.
It's there in case you can implicitly convert the pointers:
struct base {};
struct derived : base {};
std::auto_ptr<derived> d(new derived);
std::auto_ptr<base> b(d); // converts
Also, you didn't ask but you'll notice the copy-constructor is non-const. This is because the auto_ptr
will take ownership of the pointer. In the sample above, after b
is constructed, d
holds on to nothing. This makes auto_ptr
unsuitable for use in containers, because it can't be copied around.
C++0x ditches auto_ptr
and makes one called unique_ptr
. This pointer has the same goals, but accomplishes them correctly because of move-semantics. That is, while it cannot be copied, it can "move" ownership:
std::unique_ptr<derived> d(new derived);
std::unique_ptr<base> b(d); // nope, cannot be copied
std::unique_ptr<base> b(std::move(d)); // but can be moved
This makes unique_ptr
suitable for use in containers, because they no longer copy their values, they move them.
The first one is a copy constructor, then second one is a templated constructor from auto_ptr
with other template parameters.
The implementation has to provide a non-template copy constructor if it doesn't want the compiler generated one. This is because a templated constructor that could be used as a copy constructor doesn't suppress the compiler generate one and the compiler generated one would always be a better match for copy construction by virtue of not being a template.
精彩评论