为什么 auto_ptr 的接口指定两个类似复制构造函数的构造函数
我正在查看此链接上的 auto_ptr 文档 自动指针 有些事情我无法完全理解为什么要这样做。在接口部分,有两个关于其复制构造函数的声明:
1)
auto_ptr(auto_ptr<X>&) throw ();
2)
template <class Y>
auto_ptr(auto_ptr<Y>&) throw();
这是做什么用的。
I was going through the auto_ptr documentation 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它在那里,以防您可以隐式转换指针:
另外,您没有询问,但您会注意到复制构造函数是非常量的。这是因为
auto_ptr
将取得指针的所有权。在上面的示例中,构造b
后,d
不保留任何内容。这使得 auto_ptr 不适合在容器中使用,因为它无法复制。C++0x 抛弃了
auto_ptr
并创建了一个名为unique_ptr
的指针。该指针具有相同的目标,但由于移动语义而正确地实现了这些目标。也就是说,虽然它不能被复制,但它可以“移动”所有权:这使得
unique_ptr
适合在容器中使用,因为它们不再复制其值,而是移动它们。It's there in case you can implicitly convert the pointers:
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, afterb
is constructed,d
holds on to nothing. This makesauto_ptr
unsuitable for use in containers, because it can't be copied around.C++0x ditches
auto_ptr
and makes one calledunique_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:This makes
unique_ptr
suitable for use in containers, because they no longer copy their values, they move them.第一个是复制构造函数,第二个是来自
auto_ptr
以及其他模板参数的模板化构造函数。如果实现不希望编译器生成一个非模板复制构造函数,则它必须提供一个非模板复制构造函数。这是因为可用作复制构造函数的模板化构造函数不会抑制编译器生成构造函数,并且由于不是模板,编译器生成的构造函数始终更适合复制构造。
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.