Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `boost::any` better than `void*`?

What inherent advantages do boost::any and boost::any_cast offer over using void* and dynamic_cast?

like image 987
Paul Manta Avatar asked Jan 06 '12 12:01

Paul Manta


People also ask

Why is the void pointer useful when would you use it?

Why do we use a void pointer in C programs? We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.

Can void pointer be incremented?

You can not increment a void pointer. Since a void* is typeless, the compiler can not increment it and thus this does not happen.

What does the void pointer can be difference?

A void pointer is a pointer to incomplete type, so if either or both operands are void pointers, your code is not valid C. Note that GCC has a non-standard extension which allows void pointer arithmetic, by treating void pointers as pointer-to-byte for such cases.


1 Answers

The advantage is that boost::any is way more type-safe than void*.

E.g.

int i = 5;
void* p = &i;
static_cast<double*>(p);  //Compiler doesn't complain. Undefined Behavior.
boost::any a;
a = i;
boost::any_cast<double>(a); //throws, which is good

As to your comment, you cannot dynamic_cast from a void*. You can dynamic_cast only from pointers and references to class types which have at least one virtual function (aka polymorphic types)

like image 79
Armen Tsirunyan Avatar answered Sep 28 '22 01:09

Armen Tsirunyan