gpt4 book ai didi

c++ - std::aligned_storage 中的新位置?

转载 作者:IT老高 更新时间:2023-10-28 12:43:02 27 4
gpt4 key购买 nike

假设我有一个类型模板参数 T。

假设我有一个 std::aligned_storage 如下:

typename std::aligned_storage<sizeof(T), alignof(T)>::type storage;

我想将新的 T 放入 storage

要传递给placement new 运算符的符合标准的指针值/类型是什么,我如何从storage 派生它?

new (& ???) T(a,b,c);

例如:

new (&storage) T(a,b,c);
new (static_cast<void*>(&storage)) T(a,b,c);
new (reinterpret_cast<T*>(&storage)) T(a,b,c);
new (static_cast<T*>(static_cast<void*>(&storage));

以上哪项(如果有)符合要求,如果没有,更好的方法是什么?

最佳答案

最偏执的方式是

::new ((void *)::std::addressof(storage)) T(a, b, c);

解释:

  • ::std::addressof 防止 storage 上的一元 operator& 重载,这在技术上是标准允许的。 (虽然没有理智的实现会这样做。) ::std 防范任何可能在范围内的名为 std 的非顶级 namespace (或类)。
  • (void *)(在这种情况下相当于 static_cast)确保您调用放置 operator new void * 而不是像 decltype(storage) * 这样的其他东西。
  • ::new 会跳过任何特定于类的放置 operator new,确保调用转到全局位置。

总之,这保证了调用库放置 operator new 采用 void *,并且 T 是在存储在哪里。

不过,在大多数理智的程序中,

new (&storage) T(a,b,c);

应该足够了。

关于c++ - std::aligned_storage 中的新位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28187732/

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