为什么空向量会调用值类型的默认构造函数? [英] Why does an empty vector call the value type's default constructor?

查看:44
本文介绍了为什么空向量会调用值类型的默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用g ++观察到,创建大小为零的向量将一次调用向量的参数化对象类型的构造函数.然后将其删除.为什么会这样?

Using g++, I observe that creating a vector of size zero calls the vector's parameterized object type's constructor once. 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);
}

输出:

默认的s构造函数

默认的s析构函数

推荐答案

因为您要显式传递初始大小,该初始大小将调用构造函数,该构造函数具有另一个参数,其默认值为 s().只需省去(0)(即 std :: vector< s> v; )就不会发生.

Because you're explicitly passing an initial size, which calls a constructor that has another parameter whose default value is s(). Just leave out the (0) (i.e. std::vector<s> v;) and it won't happen.

为完整起见,标准23.2.4-2将您要调用的构造函数定义为:

For completeness, the Standard 23.2.4-2 defines the constructor you're calling as:

    显式矢量(size_type n,const T& value = T()
              nbsp; bsp          const Allocator&= Allocator());

    explicit vector(size_type n, const T& value =T(),
                                    const Allocator& = Allocator());

除了(与C ++ 03相关,但与C ++ 11不相关)

此构造函数的另一个有趣的行为方面也提高了S.O的意识.周期性地:当请求的元素的初始数量大于0时,它将那些元素从原型参数复制构造到构造函数中:

Another interesting behavioural aspect of this constructor also raises its head on S.O. periodically: when the initial number of elements requested is > 0, it copy-constructs those elements from the prototypal parameter to the constructor:

  • 人们经常放置一个默认构造函数,使成员变量保持未初始化状态,希望使 vector(n)几乎与基础免费存储区分配(BUT)一样快
  • 复制构造函数仍被调用n次,以将原型对象的垃圾"内容复制到每个请求的元素中
  • people often put a default constructor that leaves member variables uninitialised, hoping to make vector(n) almost as fast as the underlying free store allocation, BUT
  • the copy-constructor is still called n times to copy the "garbage" content of the prototypal object into each of the requested elements

这会带来明显的性能损失,但是如果垃圾内容中包含以下内容,也会使应用 崩溃.复制构造函数只能假定的指针有效.同样,即使 push_back 这样一个未初始化的垃圾对象也非常危险-它缺少适当的值语义封装,并且可能在向量调整大小时被复制,例如 std :: sort()是在向量等上执行的.

This has an obvious performance cost, but can also crash the application if the garbage content includes e.g. 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..

这篇关于为什么空向量会调用值类型的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆