std :: allocator_traits ::用const指针构造

And*_*nak 5 c++ allocator language-lawyer c++11 c++14

以下代码可以正常编译:

#include <iostream>
#include <memory>
int main()
{
const int * a = new int(5);

std::cout << *a << std::endl; // Prints 5

// *a = 5; // Compiler error.
using at = std::allocator_traits<typename std::allocator<int>>;
auto alloc = std::allocator<int>();
at::construct(alloc, a);

std::cout << *a << std::endl; // Prints 0
}
Run Code Online (Sandbox Code Playgroud)

隐藏在libstdc ++中

::new((void*)a) int;
Run Code Online (Sandbox Code Playgroud)

但是aconst

这是未定义的行为吗?还是新放置的位置不算作修改?我修改了的值*aconst。据我了解,这是不允许的:

通过非常量访问路径修改const对象,并通过非易失性glvalue引用volatile对象会导致未定义的行为。

https://zh.cppreference.com/w/cpp/language/const_cast

Adr*_*vry 0

const int* a指定所指向的内存槽包含的值a是常量,而不是指针本身。

#include <memory>

int main()
{
    const int * a = new int;

    a = nullptr; // Compile fine
    *a = 1; // Won't compile

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

您期望您的代码的行为如下:

#include <memory>

int main()
{
    int* const a = new int;

    a = nullptr; // Won't compile
    *a = 1; // Compile fine

    return 0;
}
Run Code Online (Sandbox Code Playgroud)