【发布时间】:2020-09-08 13:02:55
【问题描述】:
#include <iostream>
#include <vector>
using namespace std;
struct A {
int i = 0;
};
void append(vector<A>& v) {
auto a = v.back(); // is a allocated on the stack? Will it be cleaned after append() returns?
++a.i;
v.push_back(a);
}
void run() {
vector<A> v{};
v.push_back(A{}); // is A{} created on the stack? Will it be cleaned after run() returns?
append(v);
for (auto& a : v) {
cout << a.i << endl;
}
}
int main() {
run();
return 0;
}
上面的代码按预期打印:
0
1
但我有两个问题:
- A{} 是在堆栈上创建的吗? run() 返回后会清理吗?
- 是在堆栈上分配的吗? append() 返回后会被清理吗?
更新:
#include <iostream>
#include <vector>
using namespace std;
struct A {
int i = 0;
A() { cout << "+++Constructor invoked." << endl; }
A(const A& a) { cout << "Copy constructor invoked." << endl; }
A& operator=(const A& a) {
cout << "Copy assignment operator invoked." << endl;
return *this;
};
A(A&& a) { cout << "Move constructor invoked." << endl; }
A& operator=(A&& a) {
cout << "Move assignment operator invoked." << endl;
return *this;
}
~A() { cout << "---Destructor invoked." << endl; }
};
void append(vector<A>& v) {
cout << "before v.back()" << endl;
auto a = v.back();
++a.i;
cout << "before v.push_back()" << endl;
v.push_back(a);
cout << "after v.push_back()" << endl;
}
void run() {
vector<A> v{};
v.push_back(A{});
cout << "entering append" << endl;
append(v);
cout << "exited append" << endl;
for (auto& a : v) {
cout << a.i << endl;
}
}
int main() {
run();
return 0;
}
输出:
+++Constructor invoked.
Move constructor invoked.
---Destructor invoked.
entering append
before v.back()
Copy constructor invoked.
before v.push_back()
Copy constructor invoked.
Copy constructor invoked.
---Destructor invoked.
after v.push_back()
---Destructor invoked.
exited append
0
0 // I understand why it outputs 0 here. I omitted the actual work in my copy/move constructors overloads.
---Destructor invoked.
---Destructor invoked.
我更新了问题中的代码,添加了复制/移动构造函数。我发现复制构造函数在追加中被调用了 3 次。我理解 auto a = v.back();需要一个副本,但其他两个副本可能应该避免?
【问题讨论】:
-
vector 管理堆上的数据。可以在堆栈上调整向量和强制分配,但很少这样做。
-
详细信息在下面的答案中,但基本上你担心的是你不需要的事情。 C++ 确保一切都被正确清理,除非你开始使用
new。使用new分配的任何内容都是您清理的责任。这就是为什么你应该很少使用new。
标签: c++ vector scope storage-duration