【问题标题】:Is const in placement new superfluous?放置新的 const 是多余的吗?
【发布时间】:2019-07-06 12:50:27
【问题描述】:

我在尝试实现 std::any 之类的容器时遇到了这个问题。

constplacement new 中的使用是多余的吗?

如果不是,那是什么意思?

我应该在placement new 上使用std::decay 吗?

#include <iostream>

int
main() {
    auto * address = std::malloc(sizeof(std::string));

    // What does `const` means here?
    // Is it superfluous?
    // Is `std::decay` needed here too?
    new (address) std::string const("hello, world");

    // Is this undefined behaviour?
    // In the context of my code: T -> std::decay<T>
    // Here I'm just using a `std::string` as an example
    auto & str = *static_cast<std::string *>(address);

    str.append("hi");

    std::cout << str << '\n';

    return 0;
}

【问题讨论】:

  • 你不需要它。只需使用new (address) std::string{"hello world"};
  • 理论上,分配只读内存是有效的。实际上,没有人分配他们无法写入的内存。所以const in new 是没用的——如果它真的有效的话。
  • Davis weites 是 UB。如果你尝试强制转换 new 返回的指针,编译器会告诉你你正在尝试做一些非法的事情。

标签: c++ constants placement-new


【解决方案1】:

这具有未定义的行为,因为对象是 const 并且它被 append 更改。 在通过malloc 值而不是使用new 的结果获取指向string 的指针时可能存在问题:数组不能与其自己的第一个指针相互转换元素,更不用说它为其提供存储的对象(它本身只是一个 C++17 术语;这是一个活跃的领域研究,因为需要一个更好的术语)。

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 2018-11-09
    • 2018-10-22
    • 1970-01-01
    • 2012-02-01
    • 2016-01-07
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多