登録されたオブジェクトの名前が一意でなければならないシステムでは、オブジェクトのthis
ポインタを名前に使用する/含める必要があります。あなたはこのポインタのアドレスをostringstream使用して文字列としてそのostringstreamの値を入れることができます"this"ポインタを文字列に変換する
std::string name = ???(this);
登録されたオブジェクトの名前が一意でなければならないシステムでは、オブジェクトのthis
ポインタを名前に使用する/含める必要があります。あなたはこのポインタのアドレスをostringstream使用して文字列としてそのostringstreamの値を入れることができます"this"ポインタを文字列に変換する
std::string name = ???(this);
あなたはアドレスの文字列表現を使用することができますか?
...はい、他のすべての同等の回答は、これを入力するのにかかりました!
:私は???
を作成する最も簡単な方法をしたいですか?文字列としてポインタ自体をフォーマットあなたが意味
#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;
}
:
登録されたオブジェクトに一意の名前を付ける必要があるシステムでは、名前にオブジェクトのthisポインタを使用する/含める必要があります。
オブジェクトのアドレスは必ずしも一意ではありません。例:このようなオブジェクトを動的に割り当て、しばらく使用し、削除して、別のオブジェクトを割り当てます。新しく割り当てられたオブジェクトは、以前と同じオブジェクトアドレスを持つ可能性があります。
何かの固有の名前を生成する方がはるかに優れています。 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