放置新的虚假警告?

Dar*_*bik 7 c++ alignment placement-new

我有以下代码:

#include "type_traits"
#include <new>


void foo()
{
    std::aligned_storage<10,alignof(long)> storage;
    new (&storage) int(12);
}
Run Code Online (Sandbox Code Playgroud)

我有定义(与长度为10个字节)一些存储,并且我放置new荷兰国际集团的int到该位置

gcc 7.3给出以下警告:

<source>:10:10: warning: placement new constructing an object of type 'int' and size '4' in a region of type 'std::aligned_storage<10, 8>' and size '1' [-Wplacement-new=]
     new (&storage) int(12);
Run Code Online (Sandbox Code Playgroud)

如果我不正确,则此警告不正确.我在这里遗漏了什么或这个警告是虚假的吗?

Sto*_*ica 11

std::aligned_storage是一个嵌套type成员的特征.这type是正确的大小和对齐方式.特征本身可能没有数据成员,因此将获得默认对象大小,即1.

所以修复很简单:

std::aligned_storage<10,alignof(long)>::type storage;
Run Code Online (Sandbox Code Playgroud)

  • 你也可以写`std :: aligned_storage_t`.我有时通过忘记`_t`来犯这个错误(与其他类型).发现它可能非常困难 (7认同)