简体   繁体   English

在 C++ 中使用向量解除分配

[英]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?我是否需要使用 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 vector<>的关键在于它在内部为您分配内存并使您无需担心内存管理您只需像这样使用它

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.然后当temp超出范围时,存储在temp所有内存都会自动删除。

std::vector contains a internal array. std::vector包含一个内部数组。 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.其中一个直接创建MyClass ,另一个创建一个指针。

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:如果您运行withoutPointer() ,它将打印:

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.指针从未被删除,因此数据从未被破坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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