Ниже выводится код:
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;
}