5

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

regetskcob
  • 1,172
  • 1
  • 13
  • 35

5 Answers5

5

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.

Not a real meerkat
  • 5,604
  • 1
  • 24
  • 55
3

When you return by reference, as in core::matrix4&, you need an object which will still be around when the function returns. In your case, you are returning a "local temporary object", which is destructed after that function exits. In order to fix this, you need to return by value, like so:

virtual const core::matrix4 getViewMatrixAffector() const {return core::matrix4();};
//                        ^ no '&'
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • This is not possible because irrlichts source-classes define getViewmatrixAffector with the '&'... – regetskcob Feb 02 '15 at 10:20
  • In that case, create an instance of `core::matrix4` elsewhere and return a reference to it, or allocate memory for it in that function and store the pointer in some object to be deleted later. – TartanLlama Feb 02 '15 at 10:23
3

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.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
2

If it really is a local object you are returning a reference to, then you shouldn't do it, because that object will not be valid once the function getViewMatrixAffector() returns.

10100111001
  • 735
  • 15
  • 31
1

Intel C++ 14.0.3.202 gives this warning even if the reference is valid outside the function. This is just a bug I witnessed in this version, but it may also appear in others. If you use this version: just mask the warning out by wrapping your function this way:

#pragma warning(push)
#pragma warning(disable:473)
( your function definition )
#pragma warning(pop)

I´m not sure if 473 is the index of this warning - but you see the correct one in the compuler´s messages.

K. Arenhold
  • 11
  • 1
  • 2