std::vector 和构造函数
当 std::vector 创建它所包含的对象的新实例时,它会调用哪个构造函数?我的印象是它调用了默认构造函数,但如果未定义默认构造函数或者编译器正在为我执行此操作怎么办?
特别是在这样的情况下:
class Foo
{
public:
Foo(int size)
{
data = new double[size];
}
~Foo()
{
delete[] data;
}
private:
double* data;
};
std::vector<Foo> myVector;
Foo bar(5);
myVector.push_back(bar);
//stuff
当对象在构造之后大小未知时,它如何知道要分配多少内存?
Which constructor does std::vector call when it is making a new instance of the object it's containing? I am under the impression it calls a default constructor but what if one is not defined or is the compiler doing that for me?
Particularly in a case as such:
class Foo
{
public:
Foo(int size)
{
data = new double[size];
}
~Foo()
{
delete[] data;
}
private:
double* data;
};
std::vector<Foo> myVector;
Foo bar(5);
myVector.push_back(bar);
//stuff
How does it know how much memory to allocate when the object has an unknown size until after construction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
至少,要编译
std::vector
,T
必须是可复制构造和可复制分配的。如果您想使用std::vector::vector(int)
(或std::vector::resize()
),则 < code>T 必须是默认可构造的。如果不满足其中任何一个要求,代码将无法编译。...
C++03 标准,第 23.1 节(一般讨论容器):
第 20.1.4 节:
At a minimum, for
std::vector<T>
to compile,T
must be copy-constructible, and copy-assignable. If you want to usestd::vector<T>::vector(int)
(orstd::vector<T>::resize()
), thenT
must have be default-constructible. If any of these requirements are not fulfilled, the code will not compile....
C++03 standard, section 23.1 (discussing containers in general):
Section 20.1.4:
修复错误后会发生什么:
有两个
Foo
实例指向同一个data
缓冲区。它可能会工作一段时间,但最终两个对象都会被销毁,析构函数被调用两次(或更多,取决于vector
是否需要移动其内容)并且缓冲区是双倍的-freed,导致未定义的行为(通常意味着崩溃)。为了解决向量的初始内容,它复制构造您作为参数传入的模式(此参数默认为默认构造的对象,但并非必须如此):
What happens, after you fix the error:
is that you have two
Foo
instances pointing to the samedata
buffer. It will probably appear to work for a while, but eventually both objects get destroyed, the destructor is called twice (or more, depending on whether thevector
needs to move its content around) and the buffer is double-freed, resulting in undefined behavior (which usually means crash).To address the initial content of the
vector
, it copy-constructs the pattern you pass in as a parameter (this parameter defaults to a default-constructed object, but doesn't have to be):