违反const正确性[placement new]和未定义的行为

时间:2018-11-28 23:25:07

标签: c++ const c++17 compiler-optimization placement-new

我已阅读以下内容:Placement new breaks consts and references? 通过阅读C++ Meeting的Matthis Kruse的幻灯片,我对以下代码感到困惑

struct U { const int i; };
std::vector<U> B;
B.push_back({ 1 });
B.clear();
B.push_back({ 2 });
const int v = B[0].i; // <- Undefined Behavior

B.clear()仅破坏对象,B.push_back({2})使用new放置在B已分配的存储位置的开头构造新对象。

  1. 我不太明白为什么访问B[0].i是未定义的行为。
  2. 编译器是否可以缓存B[0].i并可能输出1
  3. std :: launder与这一切有什么关系?真的可以确保不会发生这类编译器优化的工具吗?

标准libcxx [llvm]实现:

template <class Tp, class Allocator>
inline typename vector<Tp, Allocator>::reference
vector<Tp, Allocator>::operator[](size_type n)
{
   assert(n < size(), "vector[] index out of bounds");
    return this->__begin_[n];
}

与幻灯片中的相同。

std 2017参考:

  • 8.3(可能违反)
  • 8.4(提及std :: launder)

0 个答案:

没有答案
相关问题