등록 된 개체의 이름이 고유해야하는 시스템에서이 개체의 이름에 this
포인터를 사용하거나 포함하고 싶습니다. 나는 간단한 방법은 생성 할 ???
여기서"this"포인터를 문자열로 변환
std::string name = ???(this);
등록 된 개체의 이름이 고유해야하는 시스템에서이 개체의 이름에 this
포인터를 사용하거나 포함하고 싶습니다. 나는 간단한 방법은 생성 할 ???
여기서"this"포인터를 문자열로 변환
std::string name = ???(this);
당신은 주소의 캐릭터 라인 표현을 사용할 수 있습니다?
std::ostringstream address;
address << (void const *)this;
std:string name = address.str();
또는 ... 예, 다른 모든 동등한 답변을 입력하는 데 걸렸습니다!
당신은이 포인터의 주소를 ostringstream 사용하고 문자열로 그 ostringstream의 값을 넣을 수 있을까? 문자열로 포인터 자체의 형식을 뜻
#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();
#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;
}
:
등록 된 개체에 고유 한 이름이 있어야하는 시스템에서이 개체의 이름에이 포인터를 사용하거나 포함하고 싶습니다.
개체의 주소가 반드시 고유하지는 않습니다. 예 : 동적으로 그러한 객체를 할당하고 잠시 사용하고 삭제 한 다음 다른 객체를 할당합니다. 새로 할당 된 객체는 이전과 동일한 객체 주소를 가질 수 있습니다.
뭔가 고유 한 이름을 생성하는 훨씬 좋은 방법이 있습니다. gensym 카운터는 다음과 같습니다.
// 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") {}
};
하지만 일단 첫 번째 객체가 파괴되면 그 객체는 존재하지 않습니다. 따라서 주소가 고유합니다 ... 첫 번째 객체를 파괴하면 이름이 필요한 데이터 구조에서도 등록이 취소됩니다. –
주소를 나타내는 16 진수 문자열로 변환 하시겠습니까? –
이 질문에 대한 답변보기 : http://stackoverflow.com/questions/1255366/how-can-i-append-data-to-a-stdstring-in-hex-format – tenfour
나쁜 생각처럼 들립니다. 객체의 신원을 메모리 위치와 연결하는 것 : 향후 버전의 애플리케이션에서 이동하려고하면 어떻게 될까? 코드가 매우 불쾌한 방법으로 중단됩니다. – akappa