How to get C++ object name in run time?

前端 未结 8 1225
失恋的感觉
失恋的感觉 2021-01-17 11:08

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

8条回答
  •  一个人的身影
    2021-01-17 12:06

    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).

提交回复
热议问题