简体   繁体   English

如何从向量指针中删除指针

[英]How to delete pointers from vector pointer

I use bison parser generator that has union type for return type productions. 我将使用具有union类型的bison解析器生成器用于返回类型的生产。

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]; 错误:将类型'class std::vector<std::__cxx11::basic_string<char>*>'参数赋予'delete',预期指针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. 当您只执行v[0]您将获得向量,因为v是一个指针,然后您需要从该向量中获取值。 You can do it by adding another array access. 您可以通过添加另一个数组访问来做到这一点。 So working code would look like delete v[0][0]; 因此工作代码看起来像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. 从指针v获取向量的另一种方法是取消引用。 Code would look like (*v)[0] . 代码看起来像(*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. 使用(*v)您将获得向量,然后数组访问将访问向量中的值。

To remove value from vector use method erase . 要从向量中删除值,请使用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. 更好的是编写没有关键字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. PS如@Dahn所述,这两个指令应该是原子的。

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

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