Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning reference to local temporary object

This code

virtual const core::matrix4& getViewMatrixAffector() const {return core::matrix4();};

results with a warning telling me "Returning reference to local temporary object"...

How to solve this warning?

As mentioned below i tried to remove the '&'... Error

like image 649
regetskcob Avatar asked Feb 02 '15 10:02

regetskcob


People also ask

Is temporary object created in return by reference?

Explanation: The temporary object is not created. If object is returned by reference, a particular memory location will be denoted with another name and hence same address values will be used.

What does it mean to return a reference to an object?

It means you return by reference, which is, at least in this case, probably not desired. It basically means the returned value is an alias to whatever you returned from the function. Unless it's a persistent object it's illegal. For example: int& foo () {


2 Answers

When you create an object as a local temporary, it is destroyed as soon as the function's scope ends. In turn, you should never return a reference to it, as this would yield Undefined Behaviour. Consider returning it by value, or returning a smart pointer to an object on the free store.

like image 130
Cássio Renan Avatar answered Oct 22 '22 08:10

Cássio Renan


Since you're not in control of the return type, you must make sure you return a valid object and not just a temporary. One solution would be a function-local static variable:

virtual const core::matrix4& getViewMatrixAffector() const
{
  static const core::matrix4 val;
  return val;
};

If you find yourself doing this in many functions (with the same type of the variable), make val a (suitably renamed) static member of the class.

like image 44
Angew is no longer proud of SO Avatar answered Oct 22 '22 07:10

Angew is no longer proud of SO