banner
cells

cells

为美好的世界献上 code

Q049

Q049#

#include <iostream>

class C {
public:
    C(int i) : i(i) { std::cout << i; }
    ~C() { std::cout << i + 5; }

private:
    int i;
};

int main() {
    const C &c = C(1);
    C(2);
    C(3);
}

Explain#

C(1) and C(2) and C(3) temporary objects are destroyed immediately after their use, constants, but when a constant reference is bound to a temporary object, the temporary object's lifetime is extended to match the lifetime of the reference it is bound to.

Although temporary objects are usually destroyed at the end of the expression, if it is bound to a reference, it will persist until the lifetime of that reference ends.

Answer#

click to see answer 127386
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.