简体   繁体   中英

How to delete pointers from vector pointer

I use bison parser generator that has union type for return type productions.

union {
    std::vector<std::string*> *vecStrPtr;
    // double num; ...
};

how delete pointer from vector pointer;

    auto v = new std::vector<std::string*>();
 //....
    v->push_back(new std::string("text"));
//...
    delete v[0]; 

error: type 'class std::vector<std::__cxx11::basic_string<char>*>' argument given to 'delete', expected pointer delete v[0];

When you do just v[0] you get the vector because v is a pointer and then you need to get value from that vector. You can do it by adding another array access. So working code would look like delete v[0][0]; . But two array accesses can be confusing when you are accessing value from one dimension array (vector).

Another way to get vector from pointer v is to dereference it. Code would look like (*v)[0] . It's more clear accessing the value. With (*v) you will get the vector and then the array access is to access the value from vector.

To remove value from vector use method erase . For more information about that method look at this link . Code example would look like:

auto v = new std::vector<std::string*>();
//....
v->push_back(new std::string("text"));
//...
delete (*v)[0];
v->erase(v->begin());

Better is to write code without keyword new. With that rule you will get less memory leaks. It makes your developing easier. But in some cases you can't use it. Your code example modified by that rule would look like:

std::vector<std::string> v;
v.push_back(std::string("text"));

//here is how to get pointers from it
std::string* ptrToElement = &(v[0]);
std::vector<std::string>* ptrToVector = &v;

The right way to free one item is:

delete (*v)[index];
v->erase(b->begin()+index);

However, You should make sure that you really want to allocate a vector in the free store. It seems usually so wrong.

PS As @Dahn mentioned, Those two instructions should be atomic.

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