Qia*_*hen 0 c++ scope vector storage-duration
#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;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码按预期打印:
0
1
Run Code Online (Sandbox Code Playgroud)
但我有两个问题:
更新:
0
1
Run Code Online (Sandbox Code Playgroud)
输出:
+++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.
Run Code Online (Sandbox Code Playgroud)
我更新了问题中的代码,添加了复制/移动构造函数。我发现复制构造函数在 append 中被调用了 3 次。我理解 auto a = v.back(); 需要一个副本,但其他两个副本也许应该避免?
C++ 规范实际上并没有说明。
与v.push_back(A{})所述A{}部分创建一个临时对象,然后将其移动或复制到载体中,然后将临时对象被丢弃。
与局部变量一样,实际上,C++ 标准实际上从未提到“堆栈”,它只说明应该如何处理生命周期。编译器可能使用“堆栈”是一个实现细节。
话虽如此,大多数 C++ 编译器将使用“堆栈”来存储局部变量。像例如可变a的append功能。至于为v.push_back(A{})您创建的临时对象需要检查生成的汇编代码。
对于生命周期,临时对象的生命周期A{}在push_back函数返回后立即结束。和生活时间a的append函数结束时,append函数返回。
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |