gpt4 book ai didi

c++ - boost::any/std::any 是否就地存储小对象?

转载 作者:IT老高 更新时间:2023-10-28 22:34:58 27 4
gpt4 key购买 nike

为了容纳任意大的对象,boost::any/std::any 肯定需要为对象分配堆空间。但是,对于大小小于或等于指针 (int,char,bool,...) 的小型类型,any 可以将值原地存储在指针槽或其他一些就地内存,而不分配堆空间。但是实现会这样做吗?

我有一个场景,我经常将小类型存储在 any 中,有时只存储较大的类型,例如 strings。代码很热,因此我在问这个问题。如果不执行优化,我可能会更好地使用自己的实现来就地存储小类型。

最佳答案

没有保证,但 [any.class] 中的 C++17 草案状态那个

Implementations should avoid the use of dynamically allocated memory for a small contained object. [ Example: where the object constructed is holding only an int.  — end example ] Such small-object optimization shall only be applied to types T for which is_­nothrow_­move_­constructible_­v<T> is true.

不幸的是,除了说 int应该可以存放在适当的位置。

关于c++ - boost::any/std::any 是否就地存储小对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41878040/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com