-3

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?

SpongeBob
  • 383
  • 3
  • 16
  • 4
    If an article on C++ is written by someone who still thinks you need to write `struct` before naming a `struct` type, I would be suspicious that they might not really know what they are talking about. Edit : That article is not very good in my opinion. Just use `std::array` or `std::vector`. – François Andrieux May 24 '19 at 14:20
  • 6
    "Enter link description here" is an instruction for you to follow – Lightness Races in Orbit May 24 '19 at 14:21
  • 3
    You should really learn from [good, proper books](https://stackoverflow.com/q/388242/560648), not random tutorials written by beginners! – Lightness Races in Orbit May 24 '19 at 14:27

2 Answers2

3

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • Why would copy not happen? I am quite confused about your last paragraph, and this is the only thing which prevents me from upvoting :) – SergeyA May 24 '19 at 14:31
  • @SergeyA There's no reason for that, but the OP was imagining that there would be, and they thought there _must_ have been a memory leak as a result because they could see the values still. I'm trying to cover _all_ the misconceptions :P – Lightness Races in Orbit May 24 '19 at 14:32
0

if default constructor doesn't destroy arr member

if default constructor doesn't destroy arr member after function finished and returned.is it true?

if it is true so in my idea it is memory leakage, not?

A memory leak happens when a pointer to a dynamically allocated object is lost without deleting the allocation. Your example doesn't contain any dynamic allocation, so it cannot have a memory leak.

eerorika
  • 232,697
  • 12
  • 197
  • 326