>
>
>
V758. Reference was invalidated because…


V758. Reference was invalidated because of 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();
}

This diagnostic is classified as: