mercredi 22 septembre 2021

Store memory address of local variable in global container

In my understanding it is not possible to store the address of a local memory in a global container, because the local variable will eventually be destroyed.

class AA {
  std::string name;
public:
  explicit AA(std::string n) : name(n) {}
  std::string getName() const {
    return name;
  }
};

class Y {
  std::vector<std::reference_wrapper<AA>> x;
public:
  void addAA(AA& aa) {
    x.emplace_back(aa);
  }
  AA& getLastA() {
    return x.back();
  }
};

void foobar(Y& y) {
  AA aa("aa");
  y.addAA(aa);
}

int main() {

  Y y;
  foobar(y);
  std::cout << y.getLastA().getName() << std::endl; // error - probably because the local aa has been destroyed.
  return 0;
}

However, I do not understand why this code works:

void foobar(Y& y, AA& aa) {
  y.addAA(aa);
}

int main() {

  Y y;
  {
    AA aa("aa");
    foobar(y,aa);
  }


  std::cout << y.getLastA().getName() << std::endl;
  return 0;
}

aa is again created in another scope and should be destroyed. However, it is possible to get its name later in main. The code works fine.

Why don't we get an error in the second case?

Aucun commentaire:

Enregistrer un commentaire