复制构造函数被调用多次

时间:2019-10-24 13:46:12

标签: copy-constructor push-back

以下代码输出:

Default ctor is called
Copy ctor is called
Default ctor is called
Copy ctor is called
Copy ctor is called

为什么每个push_back()的复制构造函数调用都增加1? 我认为应该只调用一次。 我在这里想念什么吗?请我需要详细的解释。

class A
{
public:
    A()
    {
        std::cout << "Default ctor is called" << std::endl;
    }
    A(const A& other)
    {
        if(this != &other)
        {
            std::cout << "Copy ctor is called" << std::endl;
            size_ = other.size_;
            delete []p;
            p = new int[5];
            std::copy(other.p, (other.p)+size_, p);
        }
    }
    int size_;
    int* p;
};
int main()
{
    std::vector<A> vec;
    A a;
    a.size_ = 5;
    a.p = new int[5] {1,2,3,4,5};
    vec.push_back(a);

    A b;
    b.size_ = 5;
    b.p = new int[5] {1,2,3,4,5};
    vec.push_back(b);

    return 0;
}

1 个答案:

答案 0 :(得分:1)

这是因为示例中的push_back每次都必须重新分配。如果您预先reserve的尺寸,则只会看到一份。

std::vector<A> vec;
vec.reserve(10);