【问题标题】:False warning for placement new?放置新的错误警告?
【发布时间】:2018-08-31 02:53:49
【问题描述】:

我有以下代码:

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

如果我没有错,这个警告是不正确的。我在这里遗漏了什么还是这个警告是虚假的?

【问题讨论】:

    标签: c++ alignment placement-new


    【解决方案1】:

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

    所以修复很简单:

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

    【讨论】:

    • 你也可以写std::aligned_storage_t。我有时会通过简单地忘记_t 来犯这个错误(对于其他类型)。很难发现
    猜你喜欢
    • 2013-04-24
    • 2022-12-15
    • 1970-01-01
    • 2011-08-22
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多