gpt4 book ai didi

c++ - boost static_vector 而不是 std::is_trivially_destructible

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:49:51 25 4
gpt4 key购买 nike

根据 this example (左例)

#include <array>
#include <boost/container/static_vector.hpp>

struct X {
int k;
std::array<int, 4> a;
boost::container::static_vector<int, 4> b;
~X() = default;
};

int huh()
{
std::array<X, 5> x;
return 0;
}

看起来像boost::container::static_vector<T, N>T 时可以轻易破坏是(当 b 被销毁时,不会在 X 上循环)。 huh优化为 xor eax, eax; ret (即 return 0 不遍历数组。

当我改用具有非平凡析构函数的包含类型时(右例)

#include <array>
#include <boost/container/static_vector.hpp>

struct Y {
~Y();
};

struct X {
int k;
std::array<int, 4> a;
boost::container::static_vector<Y, 4> b;
~X() = default;
};

int huh()
{
std::array<X, 5> x;
return 0;
}

有一个循环发生

    add     rbx, 1
call Y::~Y() [complete object destructor]
cmp rbx, r12
jne .L3

到目前为止,我认为这是有道理的。具有普通可破坏对象的 static_vector 占用的内存可以在恒定时间内释放,而不管实际存储了多少对象。

令我惊讶的是 std::is_trivially_destructible<boost::container::static_vector<int, 4> >::value 的值是假的。这只是一个不正确的类型特征吗?

最佳答案

boost::container::static_vector<X, N>源自 boost::container::vector<X, ...>具有一些定义的构造函数的类。即使它的所有主体在发布时都被编译器删除,该类也已经容易被破坏:

struct X
{
};

struct Y
{
~Y() = default;
};

struct Z
{
~Z() {};
};

static_assert(std::is_trivially_destructible<X>::value, ""); // Succeeds
static_assert(std::is_trivially_destructible<Y>::value, ""); // Succeeds
static_assert(std::is_trivially_destructible<Z>::value, ""); // Fails

这就是为什么它不在当前的 boost 实现中的技术原因。可以有另一个实现 std::is_trivially_destructible<boost::container::static_vector<int, 4> >::value是真的?是的,这是可能的,但我想它需要 boost::container::static_vector 的特化对于平凡可破坏的类型。

关于c++ - boost static_vector 而不是 std::is_trivially_destructible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55239440/

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