Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why strings returned by name() function is implementation defined?

Tags:

c++

typeid

rtti

Consider following example:

#include <iostream>
#include <typeinfo>
int main()
{
    int a=9;
    std::cout << typeid(a).name() << '\n';
}

Output on g++ 4.8.1 : i

Output on MSVS 2010: int

Why output is compiler depedent? What is the reason behind this? Why it is left as implementation defined? Why not same output on all compilers? Does C++ standard says it explicitly?

like image 208
Destructor Avatar asked Feb 24 '26 03:02

Destructor


2 Answers

Because compilers represent types differently and don't use the same internals.

The G++ string is the mangled type name, returning that (rather than demangling it) is less work and more efficient. Requiring compilers to demangle those strings would add more work. The standard leaves it up to implementors to decide if they want to do that.

If the standard dictated it then it would also have to specify all sorts of things, like whether to say signed long or just long and how to represent complex template instantiations that depend on other types and constants. The benefits of standardising those strings would be very small, but a large amount of work.

like image 148
Jonathan Wakely Avatar answered Feb 25 '26 18:02

Jonathan Wakely


Yes, C++ standard says it explicitly:

18.7.1$9,10 Class type_info [type.info]

const char* name() const noexcept; 

9 Returns: An implementation-defined ntbs.
10 Remarks: The message may be a null-terminated multibyte string (17.5.2.1.4.2), suitable for conversion and display as a wstring (21.3, 22.4.1.4)

like image 44
songyuanyao Avatar answered Feb 25 '26 19:02

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!