简体   繁体   中英

Deallocation using vector in c++

std::vector<char>*temp = new std:: vector<char>;
temp->push_back('a');

Do I need to deallocation the memory using delete temp? Or is the memory deallocation taken care by vector?

The very point of vector<> is that it internally allocates memory for you and insulates you from all needs to worry about memory management You simply use it like

std::vector<char> temp;
temp.push_back('a');

Then later when temp goes out of scope, all memory stored inside of temp is deleted automatically.

std::vector contains a internal array. When a vector is destroyed, that array is deleted automatically.

However, if you allocate a pointer to a vector, you need to delete it explicitly. Generally speaking, just use the vector itself, not a pointer to it.

We can see this behavior if we write our own class. This class contains some data, and it prints a message when that data gets destroyed.

class MyClass {
    int* data;
   public:
    MyClass() : data(nullptr) {}
    MyClass(int size) : data = new int[size]() {}
    ~MyClass() {
        std::cout << "Deleting data\n"; 
        delete[] data;
    }
};

Let's look at two functions. One of them just creates MyClass directly, and the other one creates a pointer.

void withoutPointer() {
    MyClass c(10);
    std::cout << "Created MyClass\n"; 
}

With pointer:

void withPointer() {
    MyClass* ptr  = new MyClass(10); 
    std::cout << "Create MyClass*\n"
    std::cout u<< "Exiting function\n"; 
}

If you run withoutPointer() , it will print:

Creating MyClass
Deleting data

This is because the destructor gets called, so the data gets deleted. On the other hand, if you run the one with the pointer, it will print:

Create MyClass*
Exiting function

The pointer was never deleted, so the data never got destroyed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM