【问题标题】:C++ stl vector for classes with private copy constructor?具有私有复制构造函数的类的 C++ stl 向量?
【发布时间】:2011-08-22 23:30:33
【问题描述】:

我们的代码中有一个类,比如C。我想创建一个C 类对象的向量。但是,复制构造函数和赋值运算符都被特意声明为private。我不想(也许是不允许)改变这一点。

还有其他干净的方式来使用/定义vector<C> 吗?

【问题讨论】:

    标签: c++ vector private copy-constructor assignment-operator


    【解决方案1】:

    你可以在这里使用移动构造函数

    #include<iostream>
    #include<vector>
    
    class Road
    {
       Road(const Road& obj){}                            //copy constructor
       Road& operator=(const Road& obj){ return *this; }  //copy assignment
    
       public:
       /*May use below commented code as well
         Road(const Road&)=delete;
         Road& operator=(const Road&)=delete;
       */
    
       Road()=default;                                    //default constructor
       Road(Road&& obj){}                                 //move constructor
       void display(){ std::cout<<"Object from myvec!\n"; }
    };
    
    int main()
    {
       std::vector<Road> myVec;
       Road obj;
       myVec.push_back(std::move(obj));
    
       myVec[0].display();
       return 0;
    }
    

    【讨论】:

    • 你有错误的移动构造函数语义。从 const 对象移动是无稽之谈。
    • 感谢@DmitryKuzminov 的指出。我的意思是也使用移动构造函数来实现目标。我已经从移动构造函数中删除了 const。
    • 还有一个问题:移动构造函数不应该抛出异常(应该是noexcept)。否则vector在重新分配缓冲区时无法保证一致性,可以优先选择复制构造函数。
    【解决方案2】:

    我只用了两个朋友就成功了:

    template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
        friend class std::vector;
    template<typename _T1, typename _T2>
        friend void std::_Construct(_T1* __p, const _T2& __value);
    

    把它们放在你的类声明中,瞧!

    我使用的是 gcc 5.3.1。

    【讨论】:

      【解决方案3】:

      不,不是,std::vector 需要可分配的概念。 C 的作者一定有充分的理由禁止这样做,您必须坚持使用他们提供的任何内容来复制/分配 C 的实例。您可以使用上面建议的指针,或者C 提供其他机制来复制/分配自身。在后一种情况下,您可以为C 编写一个可分配的代理类型。

      【讨论】:

        【解决方案4】:

        您可以访问boost library吗?

        创建一个提升向量shared pointers

           std::vector<boost:shared_ptr<C>>
        

        【讨论】:

          【解决方案5】:

          您可以改用vector&lt;C*&gt;vector&lt;shared_ptr&lt;C&gt;&gt;

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-07-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-22
            • 1970-01-01
            相关资源
            最近更新 更多