-4

I have following code

#include <iostream>
#include <vector>


struct M {
    int a = 0;
    int b = 0;

    ~M(){}
};

std::vector<M> ms;

void met(int i)
{
    // This struct 'm' does not get deleted after lifetime of function "met" is over  
    M m;
    m.a = i;
    m.b = i * i;
    ms.push_back(m);
}


int main()
{
 for(int i = 0; i < 10; i++){
   met(i);
 }
 for(int i = 0; i < 10; i++){
  std::cout << ms[i].a << " : " << ms[i].b << std::endl;
 }
 return 0;
}

// OUTPUT
0 : 0
1 : 1
2 : 4
3 : 9
4 : 16
5 : 25
6 : 36
7 : 49
8 : 64
9 : 81

As we know scope of local variable is lifetime of immediate code block. In above code, scope of struct M is lifetime function met. But in above code works fine as we can see output given below code. I was expecting undefined behavior Cause M m has to be deleted once function met return to main. Is is anything special about struct in this case?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
twid
  • 6,368
  • 4
  • 32
  • 50

3 Answers3

4

The structs in met() are, in fact, deleted. The ones in the vector are copies, made when push_back() is called.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
2

// This struct 'm' does not get deleted after lifetime of function "met" is over

Yes, it does. What you are not taking into account is that you are putting a copy of m inside of the vector, and your struct has a compiler-generated copy constructor to make a copy of the member values. m is gone when met() exits, but the vector is still alive since it has global scope, and you are outputting what is stored in the vector before it goes out of scope.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

When you store the instance variable m into the vector, that actual instance is not stored. What happens is this:

  1. Create the struct m and change its properties.
  2. Call the copy constructor of m. This is a special constructor method which is used whenever an implicit copy is requested.
  3. Put this copy into the vector.
  4. Delete the original value m as the function ends.

By default, the compiler creates a copy constructor for every struct. The default implementation is just to (shallow-)copy each member variable one-by-one. Because your member variables are just ints, they are copied over to the newly copied variable inside the vector.

This needs to be kept in mind when you have bigger structures, as the entire structure can be copied around multiple times implicitly.

metacubed
  • 7,031
  • 6
  • 36
  • 65