top | item 37202094

(no title)

brtv | 2 years ago

> 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.

discuss

order

gpderetta|2 years ago

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.

brtv|2 years ago

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.

liquidify|2 years ago

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.

nly|2 years ago

What's so nasty about it?

I find it a delight

seeknotfind|2 years ago

Works with RTTI?

brtv|2 years ago

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.