这是我的最低要求:
#include <iostream>
#include <vector>
class A {
public:
A() { std::cout << "Constructor\n"; }
~A() { std::cout << "Destructor\n"; }
};
class B {
public:
B() { v.push_back(A()); v.push_back(A()); }
private:
std::vector<A> v;
};
int main() {
B b;
return 0;
}
因此,我得到了以下输出:
Constructor // first push back
Destructor // copy destroyed
Constructor // second push back
Destructor // copy destroyed
Destructor // ???????????????
// B object goes out of scope and its vector too...
Destructor // v[0] destructor called
Destructor // v[1] destructor called
有人可以照亮吗?
在遵循Dave的评论之后:
Constructor
Copy constructor
Destructor
Constructor
Copy constructor
Copy constructor
Destructor
Destructor
Destructor
Destructor
添加一个重载的副本构造函数和一些指示要作用于哪个对象的指示符,可以使您对情况有所了解:
#include <iostream>
#include <vector>
class A {
public:
A(unsigned i): i(i) { std::cout << "Constructor " << i << std::endl; }
A(const A& a) : i(a.i) { std::cout << "Copy constructor " << i << std::endl; }
~A() { std::cout << "Destructor " << i << std::endl; }
unsigned i;
};
class B {
public:
B() { v.push_back(A(0)); v.push_back(A(1)); }
private:
std::vector<A> v;
};
int main() {
B b;
return 0;
}
第一次推送时,我们将复制并销毁该临时文件。在第二次推送时,我们先进行复制,然后复制第一个对象,然后销毁第一个对象和临时对象。最后,我们摧毁了两个物体。
我猜想std :: vector首先分配的容量为1,所以第二次推送强制重新分配?如果我强制较大的初始容量(通过v.reserve(5)
在第一次推送之前调用),则多余的副本将消失。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句