c++ - 在 C++ 中调整 vector 大小时调用一次类构造函数

标签 c++ stl

我正在尝试学习 C++ STL 中的 vector ...

我有一个 temp 类:

class temp
{
private :
    int a;
public :
    //temp() {}
    temp(int a)
    {
        std::cout<<"ctor called"<<std::endl;
        this->a=a;
    }
    void setA(int a)
    {
        this->a=a;
    }
    int getA()
    {
        return a;
    }
};

现在,在主要部分,我写道:

int main() {
    vector<temp> v;
    v.resize(7,temp(5));
    for(int i=0;i<7;i++) {
        v[i].setA(i);
    }

    for(int i=0;i<7;i++) {
        cout<<v[i].getA()<<"\t";
    }
}

我得到的输出是

ctor called
0 1 2 3 4 5 6 

我想知道为什么即使在创建类 temp 的 7 个不同对象时,构造函数也只被调用一次?

最佳答案

因为 vector 的元素是通过复制参数来初始化的。您传递的参数的创建是您的代码中唯一一次调用您编写的构造函数。您正在调用的 std::vector 中的构造函数描述为 here ,它是您调用的版本 (2)。

将复制构造器添加到您的类中以查看发生了什么:

temp(const temp& t)
{
    std::cout<<"copy-ctor called"<<std::endl;
    this->a = t->a;
}

在您的代码中,编译器为您生成了一个复制构造器,但显然没有调试输出,因此您看不到它。

关于c++ - 在 C++ 中调整 vector 大小时调用一次类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15854237/

相关文章:

c++ - 优先队列不排序

c++ - 需要在c++中以周期性时间间隔调用函数

c++ - 我想做一个 'if' 声明,如果变量小于 80 t=0 但如果变量大于 t=x-80

c++ - 小部件不会隐藏

c++ - 片段着色器中的“错误 : sampler arrays indexed with non-constant expressions are forbidden in GLSL 1. 30 及更高版本”

c++ - 是否所有 C++ STL 都会产生相同的随机数(对于相同的种子)?

c++ - 带有类模板 typedef 参数的函数模板

c++ - 统一迭代 std::vector<T> 和 std::vector<unique_ptr<T>>

c++ - std::map 构造函数的奇怪用法

c++ - 我应该使用 std::remove 从列表中删除元素吗?