Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

c++ - Using std::shared_ptr<void> to point to anything

I'm using a std::shared_ptr<void> in my application to make a smart pointer which can point to many different types of data structures like structs, vectors, matrices... basically anything. What I'm trying to do is map some names to their data structures.

I'm performing the mapping using a hashtable:

std::unordered_map<std::string, std::shared_ptr<void>>

Can I cast the std::shared_ptr<void> returned by find() back to std::shared_ptr<my_type>? If so, how?

More importantly, is this good practice? Will this increase the complexity too much as the application scales? Or, is there some other completely different, elegant approach?

EDIT

Probably cannot use `Boost.Any' since it uses RTTI.

Also cannot use a base class for all these data structures, since some of them are STL containers like std::vector.

About the shared_ptr delete issue discussed on an answer below, I read that shared_ptr performs type erasure and does store type information to know which destructor to call.

Shared void pointers. Why does this work?

Why do std::shared_ptr<void> work

Why is shared_ptr<void> not specialized?

But I'm not sure about this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not good practice. If you don't store additional type information next to your std::shared_ptr (which you can cast using static_pointer_cast) you have undefined behaviour all around. Maybe Boost.Any is an option for you?

If you want to stick with std::shared_ptr<void> please remember to provide a custom deleter function (see make shared_ptr not use delete).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...