Skip to content

Comment on The missing C++ smart pointer

Comments

std::box<T> addresses these issues by offering deep copying and automatic garbage collection

This is pretty much impossible when holding a pointer of base class. However, this is a primary reason for having pointers in the first place (polymorphism, and having abstract base classes).

In all other cases, you're probably better off with either the raw value, std::variant or std::reference_wrapper.

It is actually super easy, barely an inconvenience, as long as you know the actual dynamic type at construction time.

For example shared-ptr to base can correctly invoke the correct derived type destructor even if the destructor is not virtual.

Edit: accidentally a word.

You always know the actual dynamic type at construction time, how would you otherwise construct it?

For example shared-ptr to base can correctly invoke the correct derived type

Invoke what exactly? Im sorry I don't understand what you're trying to say here.

I guess you can force all derivied types to implement a clone() function, such that box<T> can do the deep copy, but Id consider that a fairly big inconvenience for such a simple pointer type.

No need for T to have a clone function. You can use standard type erasure techniques. Consider how std:: function or std::any is implemented.

std::variant is a nasty thing. I always try hard to find a way around it, and there is almost always a better way around it.

What's so nasty about it?

I find it a delight

Works with RTTI?

With polymorphism, you typically want base classes that provide a general interface, that many classes can derive. In places where you use this pointer-to-base, you don't need/want any knowledge of the derived type. It is an unneeded depedancy, which would only increase compile time, or worse, cause circular dependancies.

I'm not a big fan of RTTI, and not even sure if it would work here. But once you start keeping track of all derived types, you might as well use an std:: variant. It's more cache friendly too, so more performant in many cases.

AboutSource Built by g1lg1l

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