﻿# 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':

```cpp
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:

```cpp
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](https://en.cppreference.com/w/cpp/language/move_constructor) to initialize the 'a' variable with zero performance loss\.

There is also an alternative solution:

```cpp
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:

```cpp
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:

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