1

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?

RATHI
  • 5,129
  • 8
  • 39
  • 48
  • 2
    Possible duplicate of [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) Specifically with regard to `string* _name;` – Richard Critten Jun 01 '19 at 13:43
  • @RATHI A temporary object is not inserted. The vector builds a copy of the temporary object and the copy will be deleted when the vector stops to exist. – Vlad from Moscow Jun 01 '19 at 13:45
  • Ques 2: Store `string _name;` (rather than a pointer), drop manual memory allocation, and your code will work and have no leaks. Compiler-generated copy constructor, assignment and destructor would do the right thing. – Igor Tandetnik Jun 01 '19 at 14:51

0 Answers0