Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert "this" pointer to string

Tags:

c++

pointers

stl

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

like image 344
Mr. Boy Avatar asked Oct 21 '11 13:10

Mr. Boy


3 Answers

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(); 
like image 184
Nawaz Avatar answered Oct 15 '22 22:10

Nawaz


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!

like image 43
Useless Avatar answered Oct 15 '22 23:10

Useless


#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;
} 
like image 4
mloskot Avatar answered Oct 15 '22 21:10

mloskot