std::typeinfo::name() returns an
implementation-defined NTBS.
The standard does not specify what the storage duration (life-time) of this NTBS ought to be. Since programmers may store the value of the returned pointer, and then try to access the NTBS later, every implementation plays safe by never releasing the memory for the NTBS. Current implementations return the same pointer for multiple calls to
std::typeinfo::name() for the same type. So, if your program calls
template<typename T> const char* getTypeId(T &cls) for a very large number of different types, the memory required for the MTBS may be high.
Old Microsoft implementations - VS 2010 or earlier - were notorious for creating a new NTBS, each time
std::typeinfo::name() was called for the same type. In this case, you should update to a more current version.
We can check it out by writing a small program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <cstring>
#include <typeinfo>
#include <set>
static std::set< const void* > ntbs_locations ;
void dump( const std::type_info& ti )
{
const auto ptr = ti.name() ;
const void* pv = ptr ;
if( ntbs_locations.insert(pv).second )
{
static int cnt = 0 ;
std::cout << ++cnt << ". " << ptr << " (NTBS at: " << pv << ")\n" ;
}
}
int main()
{
for( int i = 0 ; i < 100 ; ++i )
{
dump( typeid( std::strtol ) ) ;
dump( typeid( std::cin.getloc() ) ) ;
dump( typeid( std::strncmp ) ) ;
dump( typeid( std::cout.rdbuf() ) ) ;
dump( typeid( typeid(int) ) ) ;
}
std::cout << "\n#ntbs: " << ntbs_locations.size() << '\n' ;
}
|
With a reasonable implementation, #ntbs would be 5, not 500.
http://coliru.stacked-crooked.com/a/89eee8b6d4a74c4e