[英]C++ stl vector for classes with private copy constructor?
There is a class in our code, say class C
. 我们的代码中有一个类,比如C
类。 I want to create a vector of objects of class C
. 我想创建一个C
类对象的向量。 However, both the copy constructor and assignment operator are purposely declared to be private
. 但是,复制构造函数和赋值运算符都是故意声明为private
。 I don't want to (and perhaps am not allowed) to change that. 我不想(也许是不允许)改变它。
Is there any other clean way to use/define vector<C>
? 有没有其他干净的方法来使用/定义vector<C>
?
您可以使用vector<C*>
或vector<shared_ptr<C>>
。
I have managed to do it by using just two friends: 我只用了两个朋友就成功了:
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);
Put them inside your class declaration and voila! 把它们放在你的班级声明中吧瞧!
I am using gcc 5.3.1. 我正在使用gcc 5.3.1。
You may use move constructor here. 你可以在这里使用move构造函数 。
#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;
}
Do you have access to the boost library ? 你有权访问升级库吗?
Create a vector of boost shared pointers . 创建一个boost 共享指针的向量。
std::vector<boost:shared_ptr<C>>
No, it isn't, std::vector
requires assignable concept. 不,它不是, std::vector
需要可分配的概念。 The authors of C must have had a good reason to prohibit this, you have to stick with whatever they provide to copy/assign instances of C
. C的作者必须有充分的理由禁止这一点,你必须坚持他们提供的任何东西来复制/分配C
实例。 Either you use pointers as suggested above, or C
provides other mechanism to copy/assign itself. 您可以使用上面建议的指针,或者C
提供其他机制来复制/分配自身。 In the latter case you could write an assignable proxy type for C
. 在后一种情况下,您可以为C
编写可分配的代理类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.