V758. Reference invalidated because of the destruction of the temporary object returned by the function.


The analyzer has detected a reference that may become invalid. This reference points to an object controlled by a smart pointer or container returned from the function by value. When the function returns, the temporary object will be destroyed, and so will the object controlled by it. The reference to that object will become invalid. An attempt to use such a reference leads to undefined behavior.

Consider the following example with smart pointer 'unique_ptr':

std::unique_ptr<A> Foo()
{
  std::unique_ptr<A> pa(new A()); 
  return pa;
}

void Foo2()
{
  const A &ra = *Foo();
  ra.foo();
}

The reference points to an object controlled by smart pointer 'unique_ptr'. When the function returns, the temporary object 'unique_ptr' will be destroyed and the reference will become invalid.

To avoid such problems, you should stop using the reference and rewrite the 'Foo2()' function as follows:

void Foo2()
{
  A a(*Foo());
  a.foo();
}

In this revised code, we do not use the reference but create a new object of type 'A'. Note that starting with C++11, you can use a move constructor to initialize the 'a' variable with zero performance loss.

There is also an alternative solution:

void Foo2()
{
  std::unique_ptr<A> pa = Foo();
  pa->foo();
}

This code relies on passing the ownership of the object of type 'A'.

Now let's discuss an example that uses the 'std::vector' container:

std::vector<A> Foo();

void Foo2()
{
  const A &ra = Foo()[42];
  ra.foo();
}

The problem here is just the same as with 'unique_ptr': the temporary object 'vector' is destroyed and the reference to its element becomes invalid.

The same is true for methods that return references to elements inside a container: front(), back(), and others:

void Foo2()
{
  const A &ra = Foo().front();
  ra.foo();
}

Do you make errors in the code?

Check your code
with PVS-Studio

Static code analysis
for C, C++, and C#

goto PVS-Studio;
We use cookies for the analysis of events to improve our content and make user interaction more convenient. By continuing the view of our web-pages you accept the terms of using these files. You can find out more about cookie-files and privacy policy or close the notification, by clicking on the button. Learn More →
Do not show