Convert “this” pointer to string

泪湿孤枕 提交于 2019-12-29 04:17:45

问题


In a system where registered objects must have unique names, I want to use/include the object's this pointer in the name. I want the simplest way to create ??? where:

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


回答1:


You could use string representation of the address:

#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(); 



回答2:


You mean format the pointer itself as a string?

std::ostringstream address;
address << (void const *)this;
std:string name = address.str();

Or ... yes, all the other equivalent answers in the time it took me to type this!




回答3:


#include <sstream>
#include <iostream>
struct T
{
    T()
    {
        std::ostringstream oss;
        oss << (void*)this;
        std::string s(oss.str());

        std::cout << s << std::endl;
    }
};

int main()
{
    T t;
} 



回答4:


You could use ostringstream the this pointer's address and put that ostringstream's value as string?




回答5:


In a system where registered objects must have unique names, I want to use/include the object's this pointer in the name.

An object's address is not necessarily unique. Example: You dynamically allocate such an object, use it for a while, delete it, and then allocate another such object. That newly allocated object might well have the same the object address as the previous.

There are far better ways to generate a unique name for something. A gensym counter, for example:

// Base class for objects with a unique, autogenerated name.
class Named {
public:
  Named() : unique_id(gensym()) {}
  Named(const std::string & prefix) : unique_id(gensym(prefix)) {}

  const std::string & get_unique_id () { return unique_id; }

private:
  static std::string gensym (const std::string & prefix = "gensym");
  const std::string unique_id;
};  

inline std::string Named::gensym (const std::string & prefix) {
  static std::map<std::string, int> counter_map;
  int & entry = counter_map[prefix];
  std::stringstream sstream;
  sstream << prefix << std::setfill('0') << std::setw(7) << ++entry;
  return sstream.str();
}   

// Derived classes can have their own prefix. For example,
class DerivedNamed : public Named {
public:
  DerivedNamed() : Named("Derived") {}
};  


来源:https://stackoverflow.com/questions/7850125/convert-this-pointer-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!