放置新的虚假警告?

时间:2018-03-21 20:05:48

标签: c++ alignment placement-new

我有以下代码:

#include "type_traits"
#include <new>


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

我定义了一些存储空间(长度为10个字节),并且newint放置到该位置

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);

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

1 个答案:

答案 0 :(得分:11)

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

所以修复很简单:

std::aligned_storage<10,alignof(long)>::type storage;