共享的指针传染媒介,在清除传染媒介以后的记忆问题

Kad*_*mir 23 c++ memory smart-pointers vector

我意识到在调用vector.clear()哪个持有共享指针之后,shared_ptr没有释放拥有的对象的析构函数.

代码示例如下所示.即使vector.clear()被调用,在共享指针之后调用的析构函数超出了范围.我的问题是 - 我是否必须通过重置它们来手动删除向量内的所有智能指针?有没有更简单的方法可以提供建议?

Output :   

constructor
I am here
destructor

Code:

#include <vector>
#include <iostream>
#include <memory>

using namespace std;

class A
{
public:
    A(){cout << "constructor" << endl;};
    ~A(){cout << "destructor"  << endl;};
};

int main( )
{
    shared_ptr<A> sharedptr (new A);
    std::vector<shared_ptr<A> > test;
    test.push_back(sharedptr);

    test.clear();
    cout << "I am here" << endl;
}
Run Code Online (Sandbox Code Playgroud)

yng*_*ccc 42

shared_ptr<A>在这种情况下,你有两个副本,一个是sharedptr变量,另一个是向量中的元素.

这样做

test.push_back(std::move(sharedptr));
Run Code Online (Sandbox Code Playgroud)

现在注意原件sharedptr有内部移动,不再可用.另一件事是什么都不做,这是shared_ptr的完全有效的用法,并且sharedptr在它超出范围后将自行清理.

  • 我想补充一点,在问题中显示的情况下,我实际上更喜欢通过`emplace_back`在向量中构造向量,以避免使用一个可访问的命名变量(`sharedptr`),其使用后将是危险的.的std :: move`. (4认同)

小智 6

当问题出现push_back增加了副本shared_ptr的载体,离开原来的晃来晃去,直到主的存在.如果不在主范围内创建shared_ptr,则不会发生此问题.只是避免在主范围内创建shared_ptr.将其作为push_back通话中的临时权利.

Output is now:   

constructor
I am almost there
destructor
I am here

New code:

#include <vector>
#include <iostream>
#include <memory>

using namespace std;

class A
{
public:
  A(){cout << "constructor" << endl;};
  ~A(){cout << "destructor"  << endl;};
};

int main( )
{
  vector<shared_ptr<A> > test;
  test.push_back(shared_ptr<A>(new A));
  cout << "I am almost there" << endl;
  test.clear();
  cout << "I am here" << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 那么maked_shared或emplace_back呢? (2认同)