Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between `boost::any` and `std::any`

Tags:

c++

c++17

boost

C++17 introduces the object container std::any, based on the boost library boost::any. My question is: Is the standardized any equivalent to the boost version, or are there differences?

A similar question has been posted about variant, and some differences exist in that case, but I could not find references about any.


EDIT: A difference I could see is the availability of the methods emplace. More than a difference in the API I'm interested to the differences between the behavior and the guarantees. For instance, different allocations would be significant for me.

like image 450
Spiros Avatar asked Mar 14 '18 13:03

Spiros


People also ask

What is boost any?

The boost::any class (based on the class of the same name described in "Valued Conversions" by Kevlin Henney, C++ Report 12(7), July/August 2000) is a variant value type based on the second category. It supports copying of any value type and safe checked extraction of that value strictly against its type.

What is std :: any?

The class any describes a type-safe container for single values of any copy constructible type. 1) An object of class any stores an instance of any type that satisfies the constructor requirements or is empty, and this is referred to as the state of the class any object.

Does std:: any allocate memory?

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.

What is boost :: variant?

Boost. Variant, part of collection of the Boost C++ Libraries. It is a safe, generic, stack-based discriminated union container, offering a simple solution for manipulating an object from a heterogeneous set of types in a uniform manner.


1 Answers

I'm interested to the differences between the behavior and the guarantees.

There aren't any behavioral differences; not really. They both have the same requirements on the ValueType (copy-constructible, and a destructor that doesn't emit exceptions). They both provide the same operations on the values they store, with pretty much identical exception guarantees.

The principle difference is that boost::any's implementation at present doesn't implement small object optimization, while std::any implementations may provide it.

like image 112
Nicol Bolas Avatar answered Oct 30 '22 01:10

Nicol Bolas