I have created a Car class.
class Car
{
public:
std::string NumberPlate;
};
RentCar supposed to keep one instance of Car.
class RentCar
{
public:
Car& GetCar()
{
if (!m_Car) {
m_Car = std::make_unique<Car>();
}
return *m_Car;
}
private:
std::unique_ptr<Car> m_Car;
};
In main, while getting the instance of Car, each time, new instances have been given.
int main()
{
RentCar rentCar;
auto car1 = rentCar.GetCar();
car1.NumberPlate = "Temp";
std::cout << "Case 1 : " << rentCar.GetCar().NumberPlate.c_str() << "\n";
rentCar.GetCar().NumberPlate = "Temp";
std::cout << "Case 2 : " << rentCar.GetCar().NumberPlate.c_str() << "\n";
}
Output is
Case 1 :
Case 2 : Temp
Why the function provides different instances?
Also what's wrong in RentCar::GetCar function?
Aucun commentaire:
Enregistrer un commentaire