[英]Why does an empty vector call the value type's default constructor?
Using g++, I observe that creating a vector of size zero calls the vector's parameterized object type's constructor once. 使用g ++,我观察到创建一个大小为零的向量会调用向量的参数化对象类型的构造函数一次。 It then is deleted.
然后它被删除。 Why does this happen?
为什么会这样?
#include <iostream>
#include <vector>
using namespace std;
class s
{
public:
s() { cout << endl << "default s constructor" << endl; }
~s() { cout << endl << "default s destructor" << endl; }
};
int main()
{
vector<s> v(0);
}
Output: 输出:
default s constructor 默认的构造函数
default s destructor 默认的析构函数
Because you're explicitly passing an initial size, which calls a constructor that has another parameter whose default value is s()
. 因为您显式传递初始大小,该大小调用具有另一个参数(默认值为
s()
的构造函数。 Just leave out the (0)
(ie std::vector<s> v;
) and it won't happen. 只要省略
(0)
(即std::vector<s> v;
)就不会发生。
For completeness, the Standard 23.2.4-2 defines the constructor you're calling as: 为了完整起见,标准23.2.4-2将您调用的构造函数定义为:
explicit vector(size_type n, const T& value =
T()
,
explicit vector(size_type n, const T& value =
T()
,
const Allocator& = Allocator());
Aside (relevant to C++03 but not C++11) 旁白(与C ++ 03相关但不与C ++ 11相关)
Another interesting behavioural aspect of this constructor also raises its head on SO periodically: when the initial number of elements requested is > 0, it copy-constructs those elements from the prototypal parameter to the constructor: 这个构造函数的另一个有趣的行为方面也定期提出SO:当请求的元素的初始数量> 0时,它将这些元素从原型参数复制构造到构造函数:
vector(n)
almost as fast as the underlying free store allocation, BUT vector(n)
几乎与底层的免费存储分配一样快,但是 This has an obvious performance cost, but can also crash the application if the garbage content includes eg pointers that the copy-constructor can only assume are valid. 这具有明显的性能成本,但是如果垃圾内容包括例如复制构造器只能假设有效的指针,则也可能使应用程序崩溃。 Similarly, it's extremely dangerous to even
push_back
such an uninitialised garbage object - it lacks proper value semantic encapsulation and may be copied as the vector resizes, algorithmic operations like std::sort()
are performed on the vector etc.. 类似地,即使
push_back
这样一个未初始化的垃圾对象也是非常危险的 - 它缺乏适当的值语义封装,并且可能在向量调整大小时被复制,像向量等执行算法操作,例如std::sort()
。
The actual constructor you are calling is (from cplusplus.com): 您正在调用的实际构造函数是(来自cplusplus.com):
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
So even though you only specify the size, a new T
object is created for second parameter, and will therefore also be destroyed at the conclusion of the constructor. 因此,即使您只指定了大小,也会为第二个参数创建一个新的
T
对象,因此也会在构造函数结束时销毁它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.