复制构造函数被多次调用
Copy constructor get called more than one time
下面的代码输出:
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;
}
这是因为您的示例中的 push_back
每次都必须重新分配。如果您 reserve
预先确定大小,那么您只会看到一份。
std::vector<A> vec;
vec.reserve(10);
下面的代码输出:
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;
}
这是因为您的示例中的 push_back
每次都必须重新分配。如果您 reserve
预先确定大小,那么您只会看到一份。
std::vector<A> vec;
vec.reserve(10);