将std :: string **转换为char ***,它恰好可以工作。怎么样? [英] Converting std::string ** to char *** and it happens to work. How?

查看:154
本文介绍了将std :: string **转换为char ***,它恰好可以工作。怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

  std :: vector< std :: string& foo {{blee},{bleck},{blah0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000}}; 
std :: string * temp = foo.data();
char *** bar = reinterpret_cast< char ***>(& temp);

for(size_t i = 0; i< foo.size(); ++ i){
std :: cout< (* bar)[i] << std :: endl;
}

显然这是粗略的代码,

http://ideone.com/2XAJYR



我想知道为什么它工作?有没有一些奇怪的规则C ++我不知道?或者它只是坏的代码和未定义的行为?



我做了一个字符串巨大的情况下,有一些小字符串优化。



改编自:投射向量std :: string to char ***

解决方案

这是非常未定义的行为。



如果字符串实现恰好包含一个指向字符串数据的指针作为其唯一的数据成员,它将显得工作,因此一个 string 具有与 char * 的数组相同的内存布局。这是至少一个流行的实现(GNU)的情况,但肯定不是你可以信赖的。


Consider the following code:

std::vector<std::string> foo{{"blee"}, {"bleck"}, {"blah0000000000000000000000000000000000000000000000000000000000000000000000000000000000"}};
std::string *temp = foo.data();
char*** bar = reinterpret_cast<char***>(&temp);

for (size_t i = 0; i < foo.size(); ++i){
    std::cout << (*bar)[i] << std::endl;
}

Clearly this is sketchy code, but it happens to work.

http://ideone.com/2XAJYR

I would like to know why it works? Are there some strange rules of C++ I don't know about? Or is it just bad code and undefined behaviour?

I made one of the strings huge in case there was some small-string optimization going on.

Adapted from: Cast a vector of std::string to char***

解决方案

It is very much undefined behaviour.

It will appear to "work" if the string implementation happens to contain a pointer to the string data as its only data member, so that an array of string has the same memory layout as an array of char*. That is the case for at least one popular implementation (GNU), but is certainly not something you can rely on.

这篇关于将std :: string **转换为char ***,它恰好可以工作。怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆