在运行时获取 C++ 对象名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/468956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:30:14  来源:igfitidea点击:

get C++ object name in run time

c++runtime

提问by Hymanhab

Can I get object's name in run time (like getting object's type via RTTI)? I want the object to be able to print its name.

我可以在运行时获取对象的名称吗(比如通过 RTTI 获取对象的类型)?我希望对象能够打印其名称。

Thanks.

谢谢。

采纳答案by KeithB

Its not possible. For on thing, an object doesn't have a unique name.

这是不可能的。对于事物,对象没有唯一的名称。

A a;
A& ar = a;  // both a and ar refer to the same object

new A;  // the object created doesn't have a name

A* ap = new A[100];  // either all 100 objects share the same name, or need to 
                     // know that they are part of an array.

Your best bet is to add a string argument to the objects constructor, and give it a name when its created.

最好的办法是向对象构造函数添加一个字符串参数,并在创建时为其命名。

回答by jpalecek

Since objects in C++ don't have any names, you cannot get them. The only thing you can get to identify an object is its address.

由于 C++ 中的对象没有任何名称,因此您无法获取它们。您唯一可以识别一个对象的是它的地址。

Otherwise, you can implement your naming scheme (which means the objects would have some char*or std::stringmember with their name). You can inspire yourself in Qt with their QObject hierarchy, which uses a similar approach.

否则,您可以实现您的命名方案(这意味着对象将具有一些char*std::string成员的名称)。您可以使用 Qt 的 QObject 层次结构来激发自己的灵感,该层次结构使用类似的方法。

回答by Martin York

The language does not give you access to that information.
By the time the code has been compiled all named objects have been translated into relative memory locations. And even these locations overlap because of optimization (ie once a variable is no longer in use its space can be used by another variable).

该语言不允许您访问该信息。
到代码编译完成时,所有命名对象都已转换为相关内存位置。甚至这些位置由于优化而重叠(即,一旦一个变量不再被使用,它的空间就可以被另一个变量使用)。

The information you need is stored in the debug symbols that are generated by most compilers but these are usually stripped from release versions of the executable so you can not guarantee they exist.

您需要的信息存储在大多数编译器生成的调试符号中,但这些通常从可执行文件的发布版本中剥离,因此您不能保证它们存在。

Even if the debug symbols existed they are all compiler/platform specfic so your code would not be portable between OS or even compilers on the same OS. If you really want to follow this course you need to read and understand how the debugger for your platform works (unless you have already written a compiler this is very non trivial).

即使存在调试符号,它们也都是编译器/平台特定的,因此您的代码无法在操作系统之间移植,甚至在同一操作系统上的编译器之间也无法移植。如果你真的想学习这门课程,你需要阅读并理解你平台的调试器是如何工作的(除非你已经编写了一个编译器,这非常重要)。

回答by Tom

This may be GCC-specific:

这可能是特定于 GCC 的:

#include <typeinfo>
#include <iostream>

template <typename T>
void foo(T t)
{
    std::cout << typeid(t).name() << std::endl;
}

回答by Simon B. Jensen

C++ doesn't really support reflection. However, a bit of googling produced a couple of alternate methods, I doubt you will find them useful though.

C++ 并不真正支持反射。然而,一些谷歌搜索产生了几种替代方法,我怀疑你会发现它们很有用。

回答by tunnuz

If you mean the name of the variable, I don't think this is possible. Maybe if you compile with the GNU Debugger option on ... but even in that way I don't think the language have constructs to do that.

如果您的意思是变量的名称,我认为这是不可能的。也许如果你使用 GNU Debugger 选项编译......但即使这样,我也不认为该语言有构造来做到这一点。

回答by zaratustra

C++ objects don't have 'names' (unless I am understanding the problem wrong) Your best hope is to name them as you make them.

C++ 对象没有“名称”(除非我对问题的理解是错误的)您最好的希望是在创建它们时命名它们。

class NamedObject
{
  String name;
  NamedObject(String argname)
  { 
    name = argname;
  }
}

NamedObject phil("phil");

回答by Greg C.

So, this is basically what I did. It's hacky, but it does the trick. I created a variadic macro that takes advantage of stringizing. Unfortunately, it becomes clumsy with the need for a _dummy parameter in order to provide the pseudo-default ctor, because you cannot omit the comma separating the named argument from the variable arguments (I even tried with gnu cpp, but was unsucessful--may I didn't try hard enough).

所以,这基本上就是我所做的。这很hacky,但它确实有效。我创建了一个利用字符串化的可变参数宏。不幸的是,它变得笨拙,需要一个 _dummy 参数来提供伪默认构造函数,因为你不能省略分隔命名参数和变量参数的逗号(我什至尝试过 gnu cpp,但没有成功——可能我不够努力)。

#include <string>

#define MyNamedClass( objname, ... ) MyClass objname(__VA_ARGS__, #objname )

class MyClass
{
public:
   MyClass( void* _dummy=nullptr, const std::string& _name="anonymous") : name( _name ) {}
   MyClass( int i, const std::string& _name="anonymous" ) : name( _name ) {}

private:
   std::string name;
};


int main()
{
   MyClass mc0;
   MyClass mc1(54321);
   MyNamedClass( mc2, nullptr);
   MyNamedClass( mc3, 12345 );

   return 0;
}