• 请不要在回答技术问题时复制粘贴 AI 生成的内容
jdz
V2EX  ›  程序员

求教一个 c++语法问题, 这段代码为何只析构一次呢

  •  
  •   jdz · Nov 22, 2020 · 2397 views
    This topic created in 2193 days ago, the information mentioned may be changed or developed.
    class excption_test
    {
    public:
    excption_test();
    ~excption_test();
    };

    excption_test::excption_test()
    {
    std::cout << "in constructor\n";
    }

    excption_test::~excption_test()
    {
    std::cout << "auto in destructor??\n";
    }

    excption_test get_ex()
    {
    excption_test c;
    return c;
    }

    int main()
    {
    excption_test m = get_ex();
    return 0;
    }

    我理解 get_ex()函数中创建了一个对象, 离开栈的时候会进行析构, 析构 c 对象, 同时调用拷贝构造函数拷贝给 main 函数中的 m 变量, 在 main 函数结束的时候再析构 m 对象
    11 replies  •  2020-11-24 16:17:28 +08:00
    hello2060
    hello2060
    Nov 22, 2020 via iPhone
    1
    很久没有搞 c++已经想不起来了,你这个 getex()对吗,确定这种写法没啥问题?
    hello2060
    hello2060
    Nov 22, 2020 via iPhone
    2
    我是只直接返回一个栈上对象
    hello2060
    hello2060
    Nov 22, 2020 via iPhone
    3
    如果可以的话看看有编译器优化吗
    jdz
    jdz
    OP
    Nov 22, 2020 via Android
    4
    @hello2060 是对的,我测试过。另外不太会看编译器优化,我觉的编译器优化不会改变程序执行结果
    codehz
    codehz
    Nov 22, 2020 via Android
    5
    @jdz RVO 是强制的,NRVO 是可选的,具体内容自己搜索
    twoconk
    twoconk
    Nov 22, 2020
    6
    楼上是正解,实际项目中通常返回堆内存,RVO 即返回值优化,可以少做一次拷贝构造。
    zhuangzhuang1988
    zhuangzhuang1988
    Nov 22, 2020
    7
    这个直接看 <深入理解 C++对象模型>
    里面有很多关于 这样的题目
    怎么重写
    sfqtsh
    sfqtsh
    Nov 22, 2020 via Android
    8
    See https://en.wikipedia.org/wiki/Copy_elision

    g++你可以加选项 -fno-elide-constructors 取消优化
    nightwitch
    nightwitch
    Nov 22, 2020
    9
    触发了编译器优化呗,不一定是 RVO,有可能 get_ex()函数整个都被 inline 了,实际上的函数体是
    int main(){
    excption_test m;
    return 0;
    }
    nightwitch
    nightwitch
    Nov 22, 2020
    10
    在 g++10.2,开最高级别的优化,你的代码实际上被编译成了

    int main()
    {
    std::cout << "in constructor\n";
    std::cout << "auto in destructor??\n";
    return 0;
    }

    见 https://godbolt.org/z/14o3WY
    0x11901
    0x11901
    Nov 24, 2020
    11
    @nightwitch 编译器比我会写代码系列
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2361 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 13:51 · PVG 21:51 · LAX 05:51 · JFK 08:51
    ♥ Do have faith in what you're doing.