从函数返回时调用构造函数和析构函数的频率

How often will the constructors and destructors be called when returning from a function?

本文关键字:析构函数 频率 构造函数 调用 函数 返回      更新时间:2023-10-16

如果我有一个如下函数:

stack fillStack(){
  stack a;
  return a;
}
void main(){
  stack s=fillStack();
}

考虑我们有一个名为 stack 的类。将调用多少个构造函数和析构函数?

以下是应该发生的事情:

stack fillStack() {
  stack a;  // constructor
  return a; // copy constructor and destructor a
}
int main(){
  stack s=fillStack(); // copy constructor and destructor of the temporary
} // destructor s

在实践中,该标准明确允许复制构造函数优化掉(这称为复制 elision)和要值到位建造。最终可能看起来像这样:

void fillStack(stack&);
int main() {
  stack s;
  fillStack(s); // with reference
}

虽然,复制构造仍然必须格式良好,即使编译器应用此转换。如果复制构造可以有副作用 这种优化可能会导致一些奇怪的行为(尝试从复制构造函数打印某些内容并观察行为在不同的优化级别上)。

由于

C++11 的移动语义。

假设没有编译器优化,它应该是 2 复制构造函数调用 - 一个从函数本地到临时返回值,一个从临时返回值到s