Ast*_*ngs 4 c++ language-lawyer c++17
采取以下措施:
#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();
}
Run Code Online (Sandbox Code Playgroud)
(当然,从更复杂的代码中缩减——我们通常不会std::string在这样一个简单的测试用例中以这种方式管理一个简单的向量)
这个程序有未定义的行为吗?我认为我们不能别名vector<T1>asvector<T2>,即使T1和T2兼容。
如果是这样,这是否会在运行时产生实际影响?
假设编译器中没有禁用严格别名。
有趣的是,GCC 9.2.0 没有给我任何警告-fstrict-aliasing -Wstrict-aliasing(live demo)。
这个程序有未定义的行为吗?
绝对地。您正在vector<string>通过对某个不相关类型的引用来访问类型的对象。那是 UB,违反了严格的别名规则。
如果是这样,这是否会在运行时产生实际影响?
UB 表示运行时的行为未定义。是的。