C++ trick #1

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 ...

5 novembre 2020 · 1 minuto · Domenico