c – std :: vector reserve方法是否需要Object类的复制构造函数
我试图将一些点保留到std :: vector中,并且出现错误我不明白:
#include <iostream> #include <string> #include <vector> using namespace std; class Foo{ public: std::string str; int i; Foo(){ this->str = ""; this->i = 0; } Foo(Foo ©Foo){ this->str = copyFoo.str; //Or get methods if private members this->i = copyFoo.i; } Foo(std::string str,int i){ this->str = str; this->i = i; } }; int main() { std::vector<Foo> fooVector; fooVector.reserve(20); // Error for(int i=0; i<20; i++){ fooVector[i] = Foo("Test",i); // Or should I use operator new? // Or should I even stick to the push_back method? } return 0; } 当然我可以不保留,它可能会工作.但现在我对它为什么现在不起作用感兴趣.我添加了复制构造函数,因为它看起来可能是我当时遇到的问题.但是在添加了复制构造函数之后,它也无法正常工作. 错误说:
问题出在哪儿?我是否需要初始化std:vector对象,或者只是将每个位置分配给对象实例? 编辑:我正在使用C 11.如果我删除复制构造函数,我在保留方法行收到以下错误: required from 'void std::_Construct(_T1*,_Args&& ---) [with _TI = Foo; _Args = {Foo&}] 这就是我首先编写复制构造函数的原因. 我不想使用resize方法,因为我希望size方法返回包含在向量中的实际Foo对象数,而不是我保留的数量. 解决方法std::vector<Foo> fooVector; fooVector.reserve(20); // Error for(int i=0; i<20; i++){ fooVector[i] = Foo("Test",i); // Or should I use operator new? // Or should I even stick to the push_back method? } 上面的代码是错误的.您正在访问容器中size()以外的元素.这样做的惯用方法是在容器上执行push_back / emplace_back来实际创建对象,而不仅仅是内存: for(int i=0; i<20; i++){ fooVector.emplace_back("Test",i); // Alternatively 'push_back' } 除此之外,在C 11中,容器中使用的类型需要复制或移动构造函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |