Take the following:
#include <vector>
#include <string>
#include <type_traits>
int main()
{
std::vector<std::string> vec{"foo", "bar"};
for (auto& el : vec)
el.std::string::~string();
auto& aliased = reinterpret_cast<
std::vector<
std::aligned_storage_t<sizeof(std::string), alignof(std::string)>
>&>(vec);
aliased.clear();
}
(whittled down from more complex code, of course — we wouldn't generally manage a simple std::string
vector this way in such a simple testcase)
Does this program have undefined behaviour? I thought that we cannot alias vector<T1>
as vector<T2>
, even if T1
and T2
are compatible.
And if so, can this be expected to have practical ramifications at runtime?
Assume strict aliasing is not disabled in the compiler.
Interestingly, GCC 9.2.0 doesn't give me any warnings with -fstrict-aliasing -Wstrict-aliasing
(live demo).