Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this reinterpret_cast problematic in principle, and/or in practice?

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).

like image 468
Asteroids With Wings Avatar asked Dec 17 '22 14:12

Asteroids With Wings


1 Answers

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.

like image 66
Nicol Bolas Avatar answered Mar 16 '23 00:03

Nicol Bolas