Question

I'm implementing a "variant" class which must have the smallest possible memory footprint and store some objects with a shared pointer mechanism.

For this, I would like to make a union within the class of all variable types. This includes some shared_ptr's.

The operator= and copy constructors must change the data type of the variant, hence switching to another member in the union. Upon switching to a shared_ptr, this one should be reset to null without deleting/deowning the pointer. Is there a way to do this?

Of course, there would be other ways to implement this but they are generally more complex, less safe or more memory consuming in my case. Any suggestion welcome though.

Thanks!

Was it helpful?

Solution

Resetting to null isn't sufficient; the implementations of std::shared_ptr I know also have a pointer to the reference count, which must be deleted as well.

You need to keep track of what is currently in the union, and use explicit calls to the destructor and placement new for construction any time the type changes (and in the constructors and the destructor).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top