Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible that a set contains two shared pointer to the same object?

In my code I have two vectors:

vector<lipid*> lipids;
vector<shared_ptr<bead> > ions;

The lipid class:

class lipid{
 public:
  lipid();
  lipid(double x, double y, bool up, int LID);
  ~lipid();
  void makeMe(int LID);
  std::tr1::shared_ptr<bead> head;
  std::tr1::shared_ptr<bead> body;
  std::tr1::shared_ptr<bead> tail;
  int LID;
  vec direction;
};

And I generate the head, body, tail beads in the constructor of the lipid.

std::tr1::shared_ptr<bead> he(new bead);
std::tr1::shared_ptr<bead> bo(new bead);
std::tr1::shared_ptr<bead> ta(new bead);
this->head = he;
this->body = bo;
this->tail = ta;

Some of the lipids heads are inserted to the ions vector by:

vector<lipid*>::iterator lit = lipids.begin();
while (lit != lipids.end()){
  lipid * l = *lit++;
  if (l->head->charge != 0) this->ions.push_back(l->head);
}

where charge is an integer property of the bead. I also have a map<vector<int>, set<shared_ptr<bead> > > to store some of the beads named boxes. To add a bead into any of the map values I use:

bead b = l->head; //b white also be accessed through a beads vector that holds a shared pointer to all beads in the simulation
vector<int> t = b->getBox(); //a function that returns a valid box
boxes[t].insert(b);

In a specific part I have a set of shared pointer named cBeads and I insert to it beads in two, separate loops; the first goes over some of the boxes and insert into the cBeads set any bead that has bean changed and the other goes over all the ions and insert them.

I know that that a shared pointer is supposed to be the owner of the pointer or something, does this mean that I can place two shared pointer, pointing to the same object in a set?

I hope any of this make sense to you.

like image 656
Yotam Avatar asked Dec 22 '22 08:12

Yotam


2 Answers

No, it isn't possible.

std::set guarantees that it containes no duplicates. Whether an instance is a duplicate of another is decided by applying the second template argument, which defaults to std::less.

The standard library provides an operator < that operates on std::shared_ptr, performing a less than comparrison on the underlying pointers.

like image 128
JoeG Avatar answered Jan 27 '23 15:01

JoeG


Consult http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/shared_ptr.htm#comparison (or TR1, or the C++11 standard).

If two shared_ptr point to the same object, then they compare as equivalent under operator<, so they're duplicates as far as std::set<shared_ptr<bead> > is concerned.

like image 20
Steve Jessop Avatar answered Jan 27 '23 14:01

Steve Jessop