Skip to content

Comment on The missing C++ smart pointerparent

Comments

It doesn't seem that complicated: they want unique_ptr that is copyable and copies the underlying pointee as well.

I think this would be way too big of a footgun: with implicit copy it would be too easy to pass box instead of box& and accidentally make copies when you didn't mean to. Box is not copy in Rust which avoids that problem, so really the equivalent in C++ would be just to add a .deepcopy() function on uniqueptr which is only implemented if the underlying type has a copy ctor.

but you can do that anyway - just copy the thing the unique_ptr points to, and make another unique_ptr point to it. but i really don't understand what copying a unique_ptr implicitly would mean.

also, c++ has (wisely, imho) rejected the concept of a "deep copy" - we just have copies, of varying depths.

but i really don't understand what copying a unique_ptr implicitly would mean.

The author is imagining box would be like unique_ptr but with an implicit copy constructor that copies the heap data:

  unique_ptr(unique_ptr<T>& o) : unique _ptr(*o) {}
Then if you have this code:
  function f(unique_ptr<int> ptr) 
  { cout << *ptr; }

  f(some_uniq); // implicitly copies the uniqueptr and its data

isn't this the semantics of any old c++ object with a copy constructor (and all the other stuff, of course)

Yeah; the difference between Box and a regular object would be the object is on the heap instead of the stack (just like it is with uniqueptr). I say its a footgun to have an implicitly copyable uniqueptr because a reasonable use of using the heap that way is for stuff too big to go on the stack, and too big would also mean you also don't want to treat copy as a trivial operation.

Often classes don't have a copy constructor if it's expensive to copy for the same reason though, which means they wouldn't be eligible for the proposed Box behavior either though so maybe its not a real problem.

All std data structures (vector, map, etc.) have a copy constructor, and running it can be arbitrarily expensive.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.