How exactly does a "reference" typedef behave?

STL containers have referenceand const_reference typedef, which in many cases I have seen (containers from boolbeing the only exceptions I can think of) can be trivially defined as

typedef value_type& reference;
typedef const value_type& const_reference;

What exactly is the semantics of these types of?

From what I understand, they should "behave like references to a value type," but what exactly does this mean?

MSDN says that reference:

A type that provides a reference to an element stored in a vector.

But what does that mean, exactly? Do they need to overload certain operators or have certain behavior? If so, what is the required behavior?

+5
3

, , . ( , pre-++ 11) - STL:

, , , . , . STL , size_t ptrdiff_t. , ? , ; C ++. , "", . . , . , size_t, , T* - (T*, T huge * ..). , . .

, :

Intel. - , : , , ptrdiff_t, size_t. , . ,

vector<int, alloc1> a(...);
vector<int, alloc2> b(...);

:

find(a.begin(), a.end(), b[1]);

b[1] a alloc2::reference, int&. . , , .

reference typedef T& . , , T&. , - (, , "" "" , "" "" ). , . ++ 11 - - . , ++ 11 w.r.t. , , .


, , ( , ...), , typedef reference, T&, - : reference , , " " reference, reference, .. , be T&; , , , , , (, "" RPC ..).

+4

:

enter image description here

reference typedef value_type&, typedef T

( , , )

+2

: " ? , . , reference value_type&, , value_type. .


You cannot overload operators by typedefs. typedefs have the same behavior as the type to which they are assigned. The reason for their typedef'd is to make them less bulky and provide a common “interface”

A reason referenceexists to prevent such things:

template<typename T>
struct foo {
  T& bar();

  typedef T& reference;
  reference baz();
}

foo<int> x;
foo<int>::T& y = x.bar(); // error! returns a T& but I can't create one!
foo<int>::reference z = x.baz(); // ok! 

It also makes a cleaner interface and allows you to use SFINAE:

template<typename T>
typename T::reference second(T::reference& t) { return t.at(1); };

template<typename T>
T& second(T& t) { return t[1]; };

std::vector v(10);
foo f(10); // type with [] overloaded but no reference typedef
second(x) = 5; // calls first def
second(f) = 3; // calls second def
+1
source

All Articles