5

It seems that std::any works just fine in GCC and Clang even when compiling with -fno-rtti.

While looking at the libc++ source I see that they just use a simple trick:

they take the address of a variable templated on a type in any so that is how they get the unique id.

But this code is active only when there is no RTTI turned on.

That got me wondering. Why do they even use RTTI in the first place? Why not always use this solution? I have no idea why typeid would be faster than simple pointer (to a static variable that is instantiated per type) comparisons.

Boann
  • 48,794
  • 16
  • 117
  • 146
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • 2
    It might be to support polymorphic types where the type of the variable doesn't match the type of the object – Alan Birtles Dec 19 '20 at 07:48
  • @AlanBirtles you mean something like this? It does not seem to work even with RTTI https://godbolt.org/z/MEc3vb – NoSenseEtAl Dec 19 '20 at 10:15
  • Could you please give a link to where the implementation uses RTTI? – xskxzr Dec 19 '20 at 12:11
  • @xskxzr you mean this? https://github.com/llvm/llvm-project/blob/main/libcxx/include/any – NoSenseEtAl Dec 19 '20 at 14:26
  • I guess standard forces them to. [link](https://eel.is/c++draft/any.nonmembers#lib:any_cast) . any::type() needs to return type_info and any_cast throws bad_­any_­cast if "operand.type() != typeid(remove_­reference_­t)". – jannarc Dec 19 '20 at 16:47
  • 1
    @jannarc Does the other solution without `typeid` have the same observable behavior? If so, since the "as-if" rule, the other solution is definitely OK. – xskxzr Dec 20 '20 at 04:12
  • MSVC STL also uses typeid https://github.com/microsoft/STL/blob/master/stl/inc/any and the code also compiles without RTTI https://godbolt.org/z/saG81M – phuclv Dec 20 '20 at 04:57

0 Answers0