Why is type_info noncopyable?

This is a question just out of interest - why are std::type_info's operator= and copy constructor private?
For one thing, the reference you get from typeid may not be identifying an object of type std::type_info (it may be some type derived from it), so copying that into some user-allocated std::type_info would slice it.
Last edited on
ok... so
1
2
3
std::type_info ti_1&=typeid(some_object);
std::type_info& ti_2&=typeid(some_other_object);
if (ti_1.operator==(ti_2)) // do something 

is still valid?
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
32
33
#include <typeinfo>
#include <typeindex>
#include <cassert>
#include <functional>
#include <iostream>

template < typename A, typename B > void foo( const A& a, const B& b )
{
     // the result of typeid() is a reference to *const* std::type_info
     const std::type_info& tinfo_a = typeid(a) ;
     const std::type_info& tinfo_b = typeid(b) ;

     // objects of type std::type_info are EqualityComparable
     bool dynamic_types_are_the_same = tinfo_a == tinfo_b ;
     bool static_types_are_the_same = typeid(A) == typeid(B) ;

     // but they are not CopyAssignable
     //std::type_info temp = tinfo_a ; // *** error, copy constructor is private



     // std::type_index provides a thin CopyAssignable, LessThanComparable wrapper
     // over std::type_info. It can be used as a key type in associative containers
     // and unordered associative containers
     // http://en.cppreference.com/w/cpp/types/type_index
     std::type_index tindex[] = { tinfo_a, tinfo_b, typeid(A), typeid(B) } ;

     assert( dynamic_types_are_the_same == ( tindex[0] == tindex[1] ) ) ;
     assert( static_types_are_the_same == ( tindex[2] == tindex[3] ) ) ;
     bool before = tindex[0] < tindex[2] ;
     std::hash<std::type_index> hash ;
     for( auto ti : tindex ) std::cout << hash(ti) << '\n' ;
}
Topic archived. No new replies allowed.