Consider the following, simplified and incomplete, implementation of a fixed-sized vector:
template<typename T>
class Vec {
T *start, *end;
public:
T& operator[](ssize_t idx) { return start[idx]; }
void pop() {
end--;
end->~T();
}
template<typename... U>
void push(U... args) {
new (end) T { std::forward<U>(args)... };
end++;
}
};
Now consider the following T:
struct T {
const int i;
};
And the following use case:
Vec<T> v;
v.push(1);
std::cout << v[0].i;
v.pop();
v.push(2);
std::cout << v[0].i;
The index operator uses the start pointer to access the object. The object at that point was destroyed by pop and another object was created in its storage location by push(2). If I read the documentation surrounding std::launder correctly, this means that the behavior of v[0] in the line below is undefined.
How is std::launder supposed to be used to correct this code? Do we have to launder start and end each time placement new is used? Current implementations of the stdlib seem to be using code similar to the one posted above. Is the behavior of these implementations undefined?
std::vectorhasn't been implementable in standard C++ since C++03. - T.C.data()'s return value (or in C++03,&v[0]) is required to allow pointer arithmetic on it, and pointer arithmetic is only defined for pointers into the same array.vector, for obvious reasons, can't actually use an array internally. - T.C.new int[N]? - Lightness Races in Orbitvectordoesn'tnewaT[N]. It allocates a block of storage and construct the elements one-by-one into that storage. - T.C.