将"this"指针转换为字符串

Mr.*_*Boy 14 c++ pointers stl

在注册对象必须具有唯一名称的系统中,我想在名称中使用/包含对象的this指针.我想要最简单的方法来创建???:

std::string name = ???(this);

Naw*_*waz 34

您可以使用地址的字符串表示形式:

#include <sstream> //for std::stringstream 
#include <string>  //for std::string

const void * address = static_cast<const void*>(this);
std::stringstream ss;
ss << address;  
std::string name = ss.str(); 
Run Code Online (Sandbox Code Playgroud)

  • `ss << this`可能会调用`operator <<`接受`T const*const`作为参数,在这种情况下你不会将地址作为字符串.这就是我的意思:http://coliru.stacked-crooked.com/a/cded799e93012de6 (6认同)
  • 我在没有强制转换为 void* 的情况下进行了测试,它也有效。由于某些原因有必要吗? (2认同)

Use*_*ess 7

你的意思是将指针本身格式化为字符串?

std::ostringstream address;
address << (void const *)this;
std:string name = address.str();
Run Code Online (Sandbox Code Playgroud)

或者......是的,所有其他等价的答案在我输入这个时间!