可能です。コンパイルが__PRETTY_FUNCTION__
or __func__
(これを参照) をサポートしている場合は、次のようにすることができます。
#include <iostream>
using namespace std;
class FileTwo{
public:
FileTwo(){
cerr<<"constructor for "<< __PRETTY_FUNCTION__ <<" at "<<&(*this)<<endl;
}
~FileTwo(){
cerr<<"Destructor for "<< __PRETTY_FUNCTION__ <<" at "<<&(*this)<<endl;
}
};
int main(){
FileTwo two;
return 0;
}
cerr
また、この出力がすぐにフラッシュされ、プログラムがクラッシュしても失われないように出力したことに注意してください。また、各オブジェクトには一意の*this
ポインターがあるため、それを使用して、特定のオブジェクトがいつ作成されているか、または削除されているかを確認できます。
私のコンピューターでの上記のプログラムの出力は次のとおりです。
constructor for FileTwo::FileTwo() at 0x7fff641cde40
Destructor for FileTwo::FileTwo() at 0x7fff641cde40
__func__
は C99 標準の識別子であることに注意してください。C++0x は、「実装定義の文字列」の形式でサポートを追加します。
__FUNCTION__
は、Visual C++ (ドキュメンテーションを参照) や gcc (ドキュメンテーションを参照) など、一部のコンパイラでサポートされている標準化前の拡張機能です。
__PRETTY_FUNCION__
は gcc 拡張機能で、同じようなことを行いますが、よりきれいです。
この質問には、これらの識別子に関する詳細情報があります。
コンパイラによっては、クラスの名前が返される場合がありますが、少し壊れている場合があります。
#include <iostream>
#include <typeinfo>
using namespace std;
class FileTwo{
public:
FileTwo(){
cerr<<"constructor for "<< typeid(*this).name() <<" at "<<&(*this)<<endl;
}
~FileTwo(){
cerr<<"Destructor for "<< typeid(*this).name() <<" at "<<&(*this)<<endl;
}
};
int main(){
FileTwo two;
return 0;
}
クラスがインスタンス化される変数の名前を取得しようとしている場合(two
あなたの場合)、私の知る限り、これを行う方法はありません。以下はそれをエミュレートします。
#include <iostream>
#include <string>
using namespace std;
class FileTwo{
public:
FileTwo(const std::string &myName) : myName(myName) {
cerr<<"constructor for "<< myName <<" at "<<&(*this)<<endl;
}
~FileTwo(){
cerr<<"Destructor for "<< myName <<" at "<<&(*this)<<endl;
}
private:
std::string myName;
};
int main(){
FileTwo two("two");
return 0;
}