Vector of shared pointers , memory problems after clearing the vector

为君一笑 提交于 2019-12-02 19:03:29

you have two copies of shared_ptr<A> in this case, one is the sharedptr variable and the other as an element in the vector.

do this instead

test.push_back(std::move(sharedptr));

note now the original sharedptr has it's internal moved and no longer usable. The other thing is don't do anything at all, this is a perfectly valid usage of of shared_ptr and sharedptr will clean up itself after it goes out of scope.

Fred Jackson

The problem arises when the push_back adds a copy of the shared_ptr to the vector, leaving the original dangling until main exists. If you don't make the shared_ptr in main scope, the problem does not happen. Just avoid making the shared_ptr in main scope. Make it as a temporary right in the push_back call.

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

Here sharedptr and the element in vector share the same object which will result in invoking constructor and destructor only once.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!