Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding temporary construction when returning by value and passing by const reference

I have a function which accepts a Large by const reference:

void func(const Large& param);

and a class which holds a Large:

class HoldsLarge {
public:
  Large GetByValue() const { return l; };

private:
  Large l;
}

If I do

HoldsLarge x;
func(x.GetByValue());

am I correct in understanding that a temporary will be copy constructed for x.GetByValue() which will by passed by reference to func? Is there something in the standard which will allow a compiler to omit the construction of the temporary altogether? After all, func only need a const reference to HoldsLarge::l.

I understand I could simply return HoldsLarge::l by const reference but I would like to prevent clients from accidentally creating a dangling reference.

like image 202
segfault Avatar asked May 19 '26 18:05

segfault


1 Answers

Compiler is allowed to change behavior (as optimization) in few cases: for NRVO, and since C++14 for new expression.

You are not in those cases.

Then; as-if rule allows any optimizations as long as observable behavior is identical.

So compiler can do the optimization only if that doesn't change the behavior.

Without knowing func, it cannot safely do that.

func might have access to x.l (or alias) from another way (as global).

For example, following func would prohibit the change.

Large* largePtr; // possibly set to &x.l by any way
void func(const Large& param)
{
    print(param.x);
    //param might be alias of largePtr
    mutate(alias->x);
    print(param.x); // const ref should see the modification
                    // whereas copy don't
}
like image 52
Jarod42 Avatar answered May 22 '26 06:05

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!