Which standard wording tells us that ref-to-const temporary lifetime extension only “works once”?

后端 未结 4 2087
后悔当初
后悔当初 2020-11-27 19:20

I was shown the following example in chat:

#include 
struct foo { ~foo() { std::cout << \"destroying!\\n\"; } };
const foo& func(co         


        
4条回答
  •  长情又很酷
    2020-11-27 20:18

    Probably I am a bit slow but to me it did not become clear what the resolution of this question is from reading the other answers. Thus I modified the code shown and wanted to summarize for others: the answer is, you get undefined behavior if you access y!

    Run this code:

    struct foo {
        int id;
        foo(int id) : id(id) { std::cout << "ctor " << id << std::endl; };
        ~foo() { std::cout << "dtor " << id << std::endl; }
    };
    const foo& func(const foo& a, const foo&) { return a; }
    
    int main(int argc, char** argv) {
        foo x(1);
        const foo& y = func(foo(2), x);
        std::cout << "main " << y.id << std::endl;
        return 0;
    }
    

    The output for me is:

    ctor 1
    ctor 2
    dtor 2
    main 2
    dtor 1
    

    But the line main 2 is undefined behavior.

提交回复
热议问题