从函数返回时调用构造函数和析构函数的频率
How often will the constructors and destructors be called when returning from a function?
如果我有一个如下函数:
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
相关文章:
- 什么时候调用组成单元对象的析构函数
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 什么时候调用析构函数
- 优先顺序:智能指针和类析构函数
- C++-明确何时以及如何调用析构函数
- 使用基类指针创建对象时,缺少派生类析构函数
- 在c++中使用向量时,如何调用构造函数和析构函数
- 重载运算符new[]的行为取决于析构函数
- 我需要知道编译器如何在cpp中使用析构函数
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 析构函数调用
- 通过引用传递-为什么要调用这个析构函数
- 对具有动态分配的内存和析构函数的类对象的引用
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- C++成员的析构函数顺序与shared_ptr
- C++ 防止在映射中放置()时调用析构函数
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- 调用析构函数以释放动态分配的内存
- 从函数返回时调用构造函数和析构函数的频率