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).
Does this program have undefined behaviour?
Absolutely. You are accessing an object of type vector<string>
through a reference to some unrelated type. That's UB, a violation of the strict aliasing rule.
And if so, can this be expected to have practical ramifications at runtime?
UB means that the behavior of the runtime is undefined. So yeah.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With