user7029947
user7029947

Reputation:

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];

Upvotes: 0

Views: 349

Answers (2)

Jirka Picek
Jirka Picek

Reputation: 599

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;

Upvotes: 1

Humam Helfawi
Humam Helfawi

Reputation: 20264

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.

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

Upvotes: 0

Related Questions