gpt4 book ai didi

c++ - 为什么 std::vector 需要 is_trivial 来进行按位移动,而不仅仅是 is_trivially_copyable ?

转载 作者:行者123 更新时间:2023-12-02 03:11:45 25 4
gpt4 key购买 nike

我在 libstdc++ STL_uninitialized.h 中看到这段代码:

  // This class may be specialized for specific types.
// Also known as is_trivially_relocatable.
template<typename _Tp, typename = void>
struct __is_bitwise_relocatable
: is_trivial<_Tp> { };

template <typename _Tp, typename _Up>
inline __enable_if_t<std::__is_bitwise_relocatable<_Tp>::value, _Tp*>
__relocate_a_1(_Tp* __first, _Tp* __last,
_Tp* __result, allocator<_Up>&) noexcept
{
ptrdiff_t __count = __last - __first;
if (__count > 0)
__builtin_memmove(__result, __first, __count * sizeof(_Tp));
return __result + __count;
}

但在我看来,memmove 对于可简单复制的对象来说是很好的,即使它们不是一般默认可构造的。在这种情况下谁关心默认构造函数?

最佳答案

我在 bugzilla 线程上询问了这个问题,他们向我指出了 https://stackoverflow.com/questions/47464819 。本质上,memcpy 不足以启动对象的生命周期,除非默认构造函数也很简单。因此,从技术上来说,就内存中的位而言,它可能是没问题的,但根据标准,这将是未定义的行为。由于这个库代码是由编译器团队编写的,如果他们认为安全,他们就有权这样做,但他们显然不相信安全性。

关于c++ - 为什么 std::vector 需要 is_trivial 来进行按位移动,而不仅仅是 is_trivially_copyable ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59690019/

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