首页 > 解决方案 > 复制构造函数被多次调用

问题描述

下面的代码输出:

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;
}

标签: copy-constructorpush-back

解决方案


这是因为push_back在您的示例中,每次都必须进行重新分配。如果您reserve提前确定尺寸,那么您只会看到一份副本。

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

推荐阅读