为什么vector.push_back(auto_ptr)不会编译? [英] Why vector.push_back(auto_ptr) wouldn't compile?

查看:226
本文介绍了为什么vector.push_back(auto_ptr)不会编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到,STL可以禁止程序员将auto_ptr放入容器中。例如下面的代码不能编译:

I learned that STL can forbid programmer putting an auto_ptr into a container. For example following code wouldn't compile:

    auto_ptr<int> a(new int(10));
    vector<auto_ptr<int> > v;
    v.push_back(a);

auto_ptr有复制构造函数,为什么这个代码甚至可以编译?

auto_ptr has the copy constructor, why this code can even compile?

推荐答案

查看 std的定义: :auto_ptr

namespace std {

    template <class Y> struct auto_ptr_ref {};


    template <class X>
    class auto_ptr {
    public:
        typedef X element_type;

        // 20.4.5.1 construct/copy/destroy:
        explicit           auto_ptr(X* p =0) throw();
                           auto_ptr(auto_ptr&) throw();
        template <class Y> auto_ptr(auto_ptr<Y>&) throw();

        auto_ptr&                      operator=(auto_ptr&) throw();
        template <class Y> auto_ptr&   operator=(auto_ptr<Y>&) throw();
        auto_ptr&                      operator=(auto_ptr_ref<X>) throw();

        ~auto_ptr() throw();

        // 20.4.5.2 members:
        X&     operator*() const throw();
        X*     operator->() const throw();
        X*     get() const throw();
        X*     release() throw();
        void   reset(X* p =0) throw();

        // 20.4.5.3 conversions:
                                    auto_ptr(auto_ptr_ref<X>) throw();
        template <class Y> operator auto_ptr_ref<Y>() throw();
        template <class Y> operator auto_ptr<Y>() throw();
    };

}

虽然有一个复制构造函数,到非 - const 。临时可能不会绑定到此,因此有效地禁止类型在任何使用临时的地方在容器内工作;此外, push_back 接受对 const 的引用,因为 const -correctness通过从 push_back 的参数拷贝构造,新的内部元素是不可能的。

Although there is a copy-constructor, it takes a reference to non-const. Temporaries may not bind to this, so the type is effectively prohibited from working inside containers in any place where temporaries are used; in addition, push_back accepts a reference to const, so due to const-correctness it's impossible for the new, internal element to by copy-constructed from push_back's argument.

(维基百科页面说,因为它的复制语义,auto_ptr可能不能用于可以在其操作中执行元素副本的STL容器;这并不意味着容器神奇地检查复制构造函数中的代码,以决定是否要让类型作为一个元素类型工作,而是关于函数签名。)

(That Wikipedia page says that "because of its copy semantics, auto_ptr may not be used in STL containers that may perform element copies in their operations"; this doesn't mean that containers magically examine the code inside the copy constructor to decide whether it wants to make the type work as an element type. Instead, it's just about the function signature.)

无论如何, std :: auto_ptr 在C ++ 11中已被弃用,因为有些人认为 std :: auto_ptr 是愚蠢的。对不起, std :: auto_ptr

Anyway, std::auto_ptr is deprecated as of C++11 because, in the opinion of some, std::auto_ptr is silly. Sorry, std::auto_ptr.

这篇关于为什么vector.push_back(auto_ptr)不会编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆