Skip to content

CWG3063 [class.temporary] Lifetime extension of temporaries to opaque lifetimes past function return #760

@hubert-reinterpretcast

Description

@hubert-reinterpretcast

Full name of submitter (unless configured in github; will be published with the issue): Hubert Tong

Reference (section label): [class.temporary]

Link to reflector thread (if any): N/A

Issue description:

P2748R5, "Disallow Binding a Returned Glvalue to a Temporary" only adds an error for functions that return references but entirely strikes the provision that prevents lifetime-extension of temporaries bound to the return value of a function. It thus creates situations whereby temporaries created within a function can be lifetime-extended to lifetimes that are opaque to the function.

Consider:

struct B { ~B(); };
struct A { const B &b; };
A foo() { return {{}}; }
void bar();
int main() {
  A a = foo();
  bar();
}

Based on guaranteed copy elision, the reference that the B temporary is bound to is the a.b from main. [class.temporary] says that the lifetime of the B temporary is extended. This requirement is not practical to implement.

Suggested resolution:

Restore [class.temporary] bullet 6.11 from C++23.

  • The lifetime of a temporary bound to the returned value in a function return statement ([stmt.return]) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions