可以从void*重新映射STL类对象吗?
#include <string>
void func(void *d)
{
std::string &s = reinterpret_cast<std::string&>(d);
}
int main()
{
std::string s = "Hi";
func(reinterpret_cast<void*>(&s));
}
Run Code Online (Sandbox Code Playgroud)
Fre*_*urk 10
使用static_cast将void指针转换回其他指针,只需确保转换回原来使用的完全相同的类型.转换为void指针不需要强制转换.
这适用于任何指针类型,包括指向stdlib中类型的指针.(从技术上讲,任何指向对象类型的指针,但这都是"指针"的含义;其他类型的指针,如指向数据成员的指针,需要进行限定.)
void func(void *d) {
std::string &s = *static_cast<std::string*>(d);
// It is more common to make s a pointer too, but I kept the reference
// that you have.
}
int main() {
std::string s = "Hi";
func(&s);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12051 次 |
| 最近记录: |