首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >const in placement是不是多余的?

const in placement是不是多余的?
EN

Stack Overflow用户
提问于 2019-07-06 20:50:27
回答 1查看 92关注 0票数 2

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

placement new中使用const是多余的吗?

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

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

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2019-07-07 00:09:27

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56914246

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档