Convert “this” pointer to string

后端 未结 5 1765
夕颜
夕颜 2020-12-14 10:08

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

相关标签:
5条回答
  • 2020-12-14 10:37

    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!

    0 讨论(0)
  • 2020-12-14 10:39
    #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;
    } 
    
    0 讨论(0)
  • 2020-12-14 10:39

    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") {}
    };  
    
    0 讨论(0)
  • 2020-12-14 10:42

    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(); 
    
    0 讨论(0)
  • 2020-12-14 10:45

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

    0 讨论(0)
提交回复
热议问题