I recently came across the std::any
class, introduced in C++17, based on boost::any
. This class can "hold an instance of any type" and auto
automatically deduces the data type of a variable.
So what is the main difference? What are the pros and cons?
std::any uses Small Buffer Optimization, so it will not dynamically allocate memory for simple types like ints, doubles… but for larger types it will use extra new . std::any might be considered 'heavy', but offers a lot of flexibility and type-safety.
In C++11, auto can be used for declaring local variables and for the return type of a function with a trailing return type. In C++14, auto can be used for the return type of a function without specifying a trailing type and for parameter declarations in lambda expressions.
The auto keyword in C++ automatically detects and assigns a data type to the variable with which it is used. The compiler analyses the variable's data type by looking at its initialization. It is necessary to initialize the variable when declaring it using the auto keyword.
The class template std::variant represents a type-safe union. An instance of std::variant at any given time either holds a value of one of its alternative types, or in the case of error - no value (this state is hard to achieve, see valueless_by_exception).
std::any
and auto
are completely different constructs.
std::any
is a container type that can hold an object of any type:
std::any a = 42; // a holds an int, but type is std::any
a = std::string{"hi"}; // ok, a holds a string now
The type of the object held by std::any
can change during the execution of the program.
auto
is a keyword that designates a placeholder type. The type of a variable with auto
is the type of the value used to initialize the variable:
auto a = 42; // a is int, for the entirety of the program
a = std::string{"hi"}; // error, a has type int
This type is determined statically, i.e. at compile time, and can never change during the execution of the program.
These constructs are not interchangeable, and so they have different use cases, and you can't compare the pros and cons of one versus the other meaningfully.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With