dimanche 2 mai 2021

Life circle of a class instance in a function

The following minimal code illustrate my confusion. Should a(x) be destroyed in function create()? Why m and a are exactly the same. Why the copy constructor is never called?

#include <iostream>
using namespace std;
class Board{
 public:
  int a[10000];
  int s = sizeof(a)/sizeof(a[0]);
  Board(int x){
    for(size_t i=0; i < s; ++i){
      a[i] = x;
    }
  };

  Board(const Board& other){
    memcpy(a, other.a, sizeof(int)*s);
    cout << "copy constructor called" << endl;
  };

  Board& operator=(const Board&) = default;
   ~Board(){
     cout << "board destroyed" << endl;
   };
};

Board create(int x){
  Board a(x);
  cout << &a << endl;
  return a;
}

Board mycreate(int x){
  return create(x);
}

int main(){
  auto m=create(3);
  cout << &m << endl;
  auto m2(mycreate(3));
  cout << &m2 << endl;
}

Output:

0x7ffee7f18cf8
0x7ffee7f18cf8
0x7ffee7f0f0a8
0x7ffee7f0f0a8
board destroyed
board destroyed

Aucun commentaire:

Enregistrer un commentaire