'Return an array without getting a Dangling pointer as result in C++

I want to return an array from a function in C++. I made this simple code to try to achieve it.

#include <iostream>
#include <vector>

std::vector<int> *getx()
{
   std::vector<int> a[2];
   a[0].push_back(0);
   a[1].push_back(1);
   return a;
}

int main()
{
   std::vector<int>* b = getx();
   return 0;
}

It works but I get this Warning:

warning C4172: returning address of local variable or temporary: a

Why if i made std::vector<int> a[2] static I solve the warning?

static std::vector<int> a[2];

Is there another way to return an array from a function without having dangling pointers warnings?

Thank you.



Solution 1:[1]

It works but I get this Warning:

Variables with automatic storage duration are automatically destroyed at the end of the scope where they are declared.

You return a pointer to an element of the automatic array and hence the returned pointer will be invalid. The behaviour of indirecting through such invalid pointer would be undefined.

Why if i made std::vector a[2] static I solve the warning?

Because if you make it static, then the variable has static storage duration rather than automatic storage duration. Hence, the array isn't destroyed at the end of its scope, and hence a pointer to its element will remain valid even after the function returns.

Is there another way to return an array from a function without having dangling pointers warnings?

It isn't possible to return an array in C++. It is however possible to return class objects, and classes can contain arrays as members. As such, you could return an instance of a class that contains the array that you want to return. There is a template for such array wrapper class in the standard library. It's called std::array.

Example:

std::array<std::vector<int>, 2> getx()
{
   return {
       std::vector<int>{0},
       std::vector<int>{1},
   };
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1