Search code examples
c++structreturn

return local struct that have array member


I read How to return a local array from a C/C++ function? topic and confused about the last code block of it:

#include <iostream> 
using namespace std; 

struct arrWrap { 
    int arr[100]; 
  ~arrWrap()
  {
    
  }
}; 

struct arrWrap fun() 
{ 
    struct arrWrap x; 

    x.arr[0] = 10; 
    x.arr[1] = 20; 

    return x; 
} 

int main() 
{ 
    struct arrWrap x = fun(); 
    cout << x.arr[0] << " " << x.arr[1]; 
    return 0; 
} 

can somebody analyze this for me what is the idea?


Solution

  • Being members of classes is the only time an array can be copied in one fell swoop like this.

    (In fact, this is how std::array works! By just wrapping a C array in a class.)

    It's safe, it's fine. When the arrWrap object is copied, so will be the array it encapsulates.

    There is no dynamic allocation and no memory leak. Even if this wasn't the case so the copy didn't happen, and you had some sort of dangling reference, being able to see the old values would not necessarily be evidence of a memory leak.