0

I have a library which persists the state of C++ objects to disk. Since the objects are defined by the end user, I use std::type_info::name() to get the object name as part of the filename to link the persisted data to corresponding objects. However, according to the C++ reference:

const char* name() const;

Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program.

std::type_info::name() does not guarantee the same value for the same type if application restarted. Worse, it even cannot guarantee distinct names for different types. And std::type_info::hash_code() is similar.

So, how can I get a distinct name/id of a C++ object that survives application restart, at least on the same operating system and architecture?

Community
  • 1
  • 1
Weijia Song
  • 153
  • 8
  • 1
    The standard clearly promises you nothing. If you want a promise from something other than the standard, then all major implementations give you such promise. – n. m. could be an AI Jun 10 '18 at 05:27
  • Have you looked into [std::type_index](http://en.cppreference.com/w/cpp/types/type_index) yet? – Killzone Kid Jun 10 '18 at 07:40
  • 1
    Write your own function template to do so (take the type as template parameter and specialize it for every type) – M.M Jun 10 '18 at 07:42
  • Your description of problem does confuse "object name" with "type id". It smells like logic error in your whole concept of serialization. Read FAQ https://isocpp.org/wiki/faq/serialization then study some serialization libraries (like boost serialization or protocol buffers). Or even better just use the real things. – Öö Tiib Jun 10 '18 at 09:38
  • @n.m. Thank you for that information. I think that help a lot! This should be easy to guarantee by the compilers. – Weijia Song Jun 11 '18 at 01:41
  • @M.M Yes, this should work. But I want to offload that burden from the end users. – Weijia Song Jun 11 '18 at 01:54
  • @ÖöTiib I have a spinlock guarded static counter to distinguish each of the objects of a type. Each object will be written in distinct files as long as type_info.name() gives me the guarantee. – Weijia Song Jun 11 '18 at 01:59

0 Answers0