2

Been using boost's disjoint_set. It has a copy constructor. To my understanding, it uses pointers that are handed over during the constructor call to access it's data and it doesn't manage memory allocation on its own. Therefore, when you make a copy, the actual data (unlike when you copy a std::vector<T>), isn't copied. You get two seemingly separate instances (cause you aren't using a reference) that access and modify the same data. This seems haphazard and the use case is not clear.

So the question is, why would you say that disjoint_set's copy constructor is useful and why would you make a copy constructor that returns a shallow copy of an instance?

AturSams
  • 7,568
  • 18
  • 64
  • 98

1 Answers1

1

you mean this one: inline disjoint_sets(const self& c) : rank(c.rank), parent(c.parent) {}? Its not clear here whether its shallow or deep copy. rank and parent are of template types : class RankPA, class ParentPA, so its up to the client of this template whether copy should be shallow or deep.

why would you make a copy constructor that returns a shallow copy of an instance?

its dangerous when you have dynamically allocated memory, instead you might consider using move semantics.

marcinj
  • 48,511
  • 9
  • 79
  • 100
  • Isn't `inline disjoint_sets(const self& c) : rank(c.rank), parent(c.parent) {}` the definition of a shallow copy as it relies on the types to have there own copy constructors? – NathanOliver Sep 01 '15 at 12:26
  • How would you use it to enable deep copy? Normally we use it like it is suggested in the [answer to this question](http://stackoverflow.com/questions/4134703/understanding-boostdisjoint-sets). `boost::disjoint_sets ds(rank.data(), parent.data()); // rank and parent are std::vector` – AturSams Sep 01 '15 at 12:28
  • @zehelvion if you must use `int*` as a template type for this class then its surely shallow copy, but maybe you could write a wrapper type that would act as `int*` and allow for deep copy. I suppose that writers of disjoint_sets left it to user to make sure this constructor is used safely. – marcinj Sep 01 '15 at 12:39
  • @NathanOliver I suppose you cant tell if this constructor is shallow or deep copy until its instantiated – marcinj Sep 01 '15 at 12:43
  • Yeah, I suppose, considering operator overloading. So... basically it's up to you to make something that behaves like a pointer but does deep copy. – AturSams Sep 01 '15 at 13:02