【问题标题】:How can I deallocate a pointer in vector?如何释放向量中的指针?
【发布时间】:2018-10-20 01:53:00
【问题描述】:

我想擦除向量中的一个指针,但我也想清空指针内容,这样它就不会存储A 对象并删除指针

#include <iostream>
#include <vector>

class A {
private:
  int a;

public:
  A(int a): a(a){}
  int getValue(){return a;}
};

int main(int argc, char const *argv[]) {
  auto a (new A(3));
  auto b (new A(4));

  A *c = a;

  std::cout << "Pointer a: " << a << '\n';
  std::cout << "Pointer b: " << b << '\n';
  std::cout << "Pointer c: " << c << '\n';

  std::vector<A*> v = {a, b};
  for (auto i : v)
    std::cout << i << " ";
  std::cout << '\n';
  v.erase(v.begin());

  std::cout << "Pointer c: " << c->getValue() << '\n';

  for (auto i : v)
    std::cout << i << " ";
  std::cout << '\n';

  return 0;
}

当我在擦除 a 后打印指针 c 时,它仍然打印 3

【问题讨论】:

  • v.erase() 从向量中移除指针,但不调用delete
  • 是的,但我怎样才能释放向量中的指针并将其内容设置为 nullptr?
  • 你之前调用过delete(例如delete *v.begin();)。我不知道您所说的“将其内容设置为nullptr”是什么意思
  • 每当我删除一个指针时,我都会写delete p;,然后写p = nulltpr;,所以当我打印p时,它会打印0x0
  • 写入 *v.begin() = nullptr; 不会影响原始指针变量,因为您在向量中存储了该指针的副本。

标签: c++ pointers vector c++17 delete-operator


【解决方案1】:

听起来你想要的是:

delete v[0];
v[0] = nullptr;

【讨论】:

    【解决方案2】:

    不确定您到底想要什么,但是...使用 C++17,您可以使用智能指针,正如 Rusk 所建议的那样。

    这样可以轻松解决vector的所有权和删除问题。

    在我看来,abv 需要共享指针 (std::shared_ptr),c 需要弱指针 (std::weak_ptr)。

    因此,当(且仅当)至少有一个 std::shared_ptr 维护指针的所有权时,您可以使用 c

    以下是一个没有ab的简化示例,其中v重命名为vsp(用于“共享指针向量”),c重命名为wp(用于“弱指针”) ")。

    #include <iostream>
    #include <memory>
    #include <vector>
    
    class A 
     {
       private:
          int a;
    
       public:
          A (int a0) : a{a0}
           { }
    
          int getValue ()
           {return a;}
     };
    
    int main ()
     {
       std::vector<std::shared_ptr<A>> vsp;
    
       vsp.emplace_back( new A{3} );
       vsp.emplace_back( new A{4} );
    
       std::weak_ptr<A> wp { vsp.front() };
    
       std::cout << "Pointer 0:  " << vsp[0] << " (" << vsp[0]->getValue() << ')' 
          << std::endl;
       std::cout << "Pointer 1:  " << vsp[1] << " (" << vsp[1]->getValue() << ')' 
          << std::endl;
    
       if ( auto sp = wp.lock() )
          std::cout << "Pointer wp: " << sp << " (" << sp->getValue() << ')'
             << std::endl;
       else
          std::cout << "Pointer wp: <deleted>" << std::endl;
    
       vsp.clear();
    
       std::cout << "Vector cleared" << std::endl;
    
       if ( auto sp = wp.lock() )
          std::cout << "Pointer wp: " << sp << " (" << sp->getValue() << ')'
             << std::endl;
       else
          std::cout << "Pointer wp: <deleted>" << std::endl;
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 2014-09-05
      • 1970-01-01
      相关资源
      最近更新 更多