I am learning C++ more deeply. In the journey while learning Resource allocation in C++, was trying to learn how to properly use the classes with std::vector.
#include <iostream>
#include <vector>
using namespace std;
//
class Car
{
string* _name;
public:
Car(string name="Safari")
{
_name = new string(name);
cout<<*_name<<" car is build"<<endl;
}
void drive()
{
cout<<*_name<<" is getting driven"<<endl;
}
// ~Car()
// {
// delete _name;
// }
// Car(const Car& rhs) = delete;
};
int main()
{
vector<Car> garage;
garage.push_back(Car("Honda"));
garage.back().drive();
}
Ques 1: In this program,I am inserting the custom object in vector. I was assuming that this program should crash while accessing the drive() of the vector content because in this case temporary object should have been inserted in the vector which should have been freed after the push_back() but that is not the case here.
But, If I tried to free the pointer in destructor, but in that case it is crashing after inserting the data in vector in push_back(). Could anyone explain what is happening here?
Ques 2: As per the knowledge gathered I learned that, one should delete the copy and assignment operator to stop such kind of behaviour and use the pointer in STL (vector or shared_ptr). Is this enough?