Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test behaviour of expressions containing temporaries #20

Open
GPMueller opened this issue Mar 24, 2022 · 3 comments
Open

Test behaviour of expressions containing temporaries #20

GPMueller opened this issue Mar 24, 2022 · 3 comments

Comments

@GPMueller
Copy link
Contributor

For a very simple example, see https://godbolt.org/z/xd7abze85

Complex expressions might trigger the creation of temporaries, which might make problems even when the data memory addresses are still valid. Something like auto vf_res2 = vf1 + vf1.cross(vf2); might lead to undefined behaviour when accessing vf_res2[...] later on.

Unit tests should be written to cover the expected behaviour and guidelines should be written to explain what to avoid.

@NOhs
Copy link

NOhs commented Mar 24, 2022

Am I missing something? In your example, you take the reference to a temporary, so in the next line already, your temporary goes out of scope and is gone. How is this intended to work?

@GPMueller
Copy link
Contributor Author

I thought that lifetime extension through binding const &s would make this work. Intuitively one might expect the resulting expression to be constructed such that it could be evaluated.

@NOhs
Copy link

NOhs commented Mar 24, 2022

Hm, but I only know this to work locally. I don't think you can hand them around everywhere and have this work.

A temporary bound to a reference member in a constructor’s ctor-initializer (§12.6.2 [class.base.init]) persists until the constructor exits. A temporary bound to a reference parameter in a function call (§5.2.2 [expr.call]) persists until the completion of the full expression containing the call.

However, while the above quote explains why the example does not work, it does of course provide no insight, why this was defined like this and I couldn't find a satisfying answer online so far.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants