我已阅读以下内容: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
已分配的存储位置的开头构造新对象。
B[0].i
是未定义的行为。B[0].i
并可能输出1
?标准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参考: