内部 FileTwo.h
#include"iostream"
using namespace std ;
class FileTwo{
public:
FileTwo(){
cout<<"constructor for";//Here want to show the object for which the constructor has been called
}
~Filetwo(){
cout<<"Destructor for ";//Here want to show the object for which the destructor has been called
};
在 main.cpp 中
#include"Filetwo.h"
int main(){
FileTwo two ;
return 0;
}
我知道这个示例程序很小,所以我们可以找出调用构造函数和析构函数的对象。但是对于大项目有没有办法知道对象名称?提前致谢。
最佳答案
这是可能的。如果您的编译支持 __PRETTY_FUNCTION__
或 __func__
(参见 this),那么您可以这样做:
#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++(参见 documentation)和 gcc(参见 documentation)。
__PRETTY_FUNCION__
是一个 gcc 扩展,它做同样的事情,但更漂亮。
This question有关于这些标识符的更多信息。
根据您的编译器,这可能会返回类的名称,尽管它可能有点困惑。
#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;
}
关于c++ - 在析构函数中显示对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14211462/