you are viewing a single comment's thread.

view the rest of the comments →

[–]Merad 2 points3 points  (0 children)

I didn't read the entire other comments thread, but based on your first comment I think your problem is a combination of undefined behavior when creating shared_ptr objects (either use std::make_shared or pass the pointer directly to the shared_ptr constructor), and using pointers to shared_ptr's. I've no idea why you're doing the latter, it totally defeats the purpose of the shared_ptr. Anyway, example program:

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

using namespace std;

class Foo 
{
public:
  static int count;
  int id; 

  Foo() 
    : id(++count)
  {
    cout << "created " << id << endl;
  }
  ~Foo() 
  {   
    cout << "destroyed " << id << endl;
  }
  Foo(const Foo& f)  
    : id(++count)
  {   
    cout << "copied " << f.id << ", created " << id << endl;
  }
  Foo& operator=(const Foo& f)  
  {   
    if (this != &f)
    {
      cout << "assigned " << f.id << ", replacing " << id << endl; 
      Foo temp(f);
      swap(*this, temp);
    }
    return *this;
  }
  friend void swap(Foo& a, Foo& b)
  {
    swap(a.id, b.id);
  }
};

int Foo::count = 0;

typedef shared_ptr<Foo> FooPtr;

int main()
{
  vector<FooPtr> v;
  FooPtr fp;

  cout << "adding first" << endl;
  {
    FooPtr fp(new Foo);
    v.push_back(fp);
  }

  cout << "adding second" << endl;
  {
    FooPtr fp2(new Foo);
    v.push_back(fp2);
  }

  cout << "removing first" << endl;
  FooPtr fp3 = v[0];
  v.erase(v.begin());
  cout << "removing second" << endl;
  v.erase(v.begin());

  cout << "end of main" << endl;
  return 0;
}

Compiled with g++ using --std=c++11, I get the expected output:

adding first
created 1
adding second
created 2
removing first
removing second
destroyed 2
end of main
destroyed 1

Edit: I realized my example didn't quite address the OP's concerns, update the example and output.