The following code compiles fine:
#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
}
Under the hood libstdc++ does
::new((void*)a) int;
but a
is const
!
Is this undefined behavior? Or does placement new not count as modifying?
I modified the value of *a
, which is const. To my understanding this is not allowed:
Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior.