简体   繁体   中英

std::shared_ptr in a union

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM