c++ - 临时对象销毁

标签 c++ temporary

<分区>

为什么在评估完整表达式后不调用临时对象的析构函数:

#include <iostream>


struct A 
{
    int a;
    A();
    ~A();
};

A::~A()
{
    std::cout << "~A()" << std::endl; 
}

A::A()
{
    std::cout << "A()" << std::endl; 
} 



int main()
{
    A b = A(); //Constructing of temporary object and applies copy-initalization
    std::cout << "side effect" << std::endl;
    //Destructor calling.
}

DEMO

输出:

A()
side effect
~A()

但是 12.2/3 [class.temporary] 说:

When an implementation introduces a temporary object of a class that has a non-trivial constructor (12.1, 12.8), it shall ensure that a constructor is called for the temporary object. Similarly, the destructor shall be called for a temporary with a non-trivial destructor (12.4). Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.

最佳答案

使用您的编译器和选项,临时文件被省略(优化掉),这是允许的。

因此没有临时的。

因此不存在缺失的构造函数和析构函数调用对。


同样值得注意的是,复制和移动构造函数是唯一允许编译器假设构造函数没有副作用的构造函数,即使它知道得更多。

C++11 §12.8/31:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. […]

关于c++ - 临时对象销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26324347/

相关文章:

c++ - 将文件存储在 unsigned char 数组中并打印

C++ RPC 教程?

git - 哪些 git 命令可以删除你的 stash ?

c++ - 平凡与非平凡类型的复制省略差异

c++ - 严格的别名规则和放置新

c++ - 如何正确初始化全局变量?

c++ - "map <string, int> instance[numberFeatures];"中的方括号是什么意思

c++ - 为什么写入临时流失败?

c++ - 关于cppreference.com对decltype解释的2个问题

mongodb - 如何删除 mongoDB 中的临时 MapReduce 集合