#1pitfall in return-by-ref: pointee lifetime

See the post on using out parameter to return by ref

Q: Return by reference is very common in C++, but there’s a common pitfall, that everyone must always remember?
A: pointee object’s lifetime (not “scope”).

Q2: common, practical safeguards?
A: return a field by reference, where the host object has a longer lifetime
A: return a static object by reference, either class-static, global variables, or function-static. P150 [[NittyGrittyC++]] has a useful example.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s