Can placement-new and vector::data() be used to replace elements in a vector?

て烟熏妆下的殇ゞ 提交于 2019-11-30 06:37:12

This is illegal, because 3.8p7, which describes using a destructor call and placement new to recreate an object in place, specifies restrictions on the types of data members:

3.8 Object lifetime [basic.life]

7 - If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object [...] can be used to manipulate the new object, if: [...]
— the type of the original object [...] does not contain any non-static data member whose type is const-qualified or a reference type [...]

So since your object contains a const data member, after the destructor call and placement new the vector's internal data pointer becomes invalid when used to refer to the first element; I think any sensible reading would conclude that the same applies to other elements as well.

The justification for this is that the optimiser is entitled to assume that const and reference data members are not respectively modified or reseated:

struct A { const int i; int &j; };
int foo() {
    int x = 5;
    std::vector<A> v{{4, x}};
    bar(v);                      // opaque
    return v[0].i + v[0].j;      // optimised to `return 9;`
}

@ecatmur's answer is correct as of its time of writing. In C++17, we now get std::launder (wg21 proposal P0137). This was added to make things such as std::optional work with const members amongst other cases. As long as you remember to launder (i.e. clean up) your memory accesses, then this will now work without invoking undefined behaviour.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!