c++ - 在析构函数中显示对象名称

标签 c++ object constructor destructor

内部 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/

相关文章:

C++检测是否声明了全局变量

java - 提取封装在对象中的数组

c++ - 基数到派生到构造函数中的另一个基数转换段错误 - 无效代码或编译器错误?

c++ - 如何在具有依赖元素类型的模板类构造函数中初始化 vector

c++ - str.clear() 和 str = ""之间的区别

C++静态常量类成员初始化

c++ - 对 null 对象的函数调用返回的 bool 值

java - 如何比较对象的私有(private)数据字段以确保它们相同(Java)?

Javascript 检查对象是否为空或 null 字段和数组

java - 什么是初始化 block ?