What exactly happens when returning a const reference to a local object?

struct A {
    A(int) : i(new int(783)) {
        std::cout << "a ctor" << std::endl;
    }

    A(const A& other) : i(new int(*(other.i))) {
        std::cout << "a copy ctor" << std::endl;
    }

    ~A() {
        std::cout << "a dtor" << std::endl;
        delete i;
    }

    void get() {
        std::cout << *i << std::endl;
    }

private:
    int* i;
};

const A& foo() {
    return A(32);
}

const A& foo_2() {
    return 6;
}

int main()
{
    A a = foo();
    a.get();
}

I know that returning references to local values ​​is bad. But, on the other hand, a constant reference should extend the temporary lifetime of an object.

This code creates UB output. So no life extension.

Why? I mean, can someone explain what is going on step by step?

Where is the error in my logical chain?

Foo ():

  • A (32) - ctor

  • return A (32) - creates a const reference to the local object and returns

  • A a = foo (); - a is initialized with the return value foo (), the return value goes beyond the scope (outside the expression) and is destroyed, but a is already initialized;

(But actually, the destructor is called before the copy constructor)

foo_2 ():

  • return 6 - A , ( )

  • A a = foo(); - a foo(), ( ) , a ;

( )

+5
2

. ,

12.2

5 - . [...] return (6.6.3) . [...]

. -.

, , , - , . , , , . , . .

foo, foo_2 undefined, - .

+11

" ". foo,

A foo() {
    return A(32);
}
int main() {
    const A& a = foo();
}

foo , const , , .

@AndreyT, const &. , foo, , , const & ( &) foo foo. const & main, , .

, , , , A , . A , (.. ), .

+3

All Articles