Attenzione a questo tipo di errore a cui sono soggetti gli smart pointer di C++.
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class Person {
public:
string name;
Person(string n)
: name(n) {}
~Person() {
cout << name << " destroyed" << endl;
}
};
class Car {
public:
Car(string d, string p)
:driver(d)
,passenger(p) {}
string model;
shared_ptr<Person> drv() { return shared_ptr<Person>(&driver); }
Person driver;
Person passenger;
~Car() {
cout << model << " destroyed" << endl;
}
};
int main()
{
shared_ptr<Person> drv;
{
Car astra("Domenico", "Andrea");
astra.model = "Astra K";
drv = astra.drv();
}
cout << "Car's scope destroyed" << endl;
// Do you expect drv in a valid state?
cout << "Using " << drv->name << endl; // Crash!
return 0;
}
Compila ed esegui
[ddiiorio@ddiiorio ~]$ g++ main.cpp -o main
[ddiiorio@ddiiorio ~]$ ./main
Astra K destroyed
Andrea destroyed
Domenico destroyed
Car's scope destroyed
Using Domenico10pU����Astra K!�@�f6�QAborted (core dumped)