Std :: back_inserter requires const_reference for an older GCC. What for?

I am currently looking at code that can be compiled on later versions of GCC, but not on older ones. In my case, I use std::back_inserterto std::copysome data from one data structure in a user data structure. If I forget the typedef value_type & const_referencetypedef in this custom data structure, this will not compile in GCC 4.4. The same code compiles and works fine on GCC 4.5.

What is the difference between these two versions of the compiler, which makes compiling the code on one version, but not on the other. I guess this has something to do with the C ++ 11 implementation, which was much less complete in GCC 4.4. Maybe something with decltypeor another new C ++ 11 keyword, I would suggest.

Is this code also true if I use std::back_inserterwithout type definition const_reference? I used to think that it is necessary to perform a complete set of typedefs ( value_type, reference, const_referenceetc.) to be compatible with the STL-algorithms library? Or, I can safely assume that if my code compiles in this case, I will not cause anything dangerous (for example, moving semantics that will destroy my other data structure).

+5
source share
2 answers

The standard (1998) states what std::back_insert_iteratoris required Container::const_reference. In "24.4.2.1 Template class back_insert_iterator", [lib.back.insert.iterator], he says:

back_insert_iterator<Container>&
operator=(typename Container::const_reference value);

Standard, 2011 only wants Container::value_type,

back_insert_iterator<Container>&
operator=(const typename Container::value_type& value);
back_insert_iterator<Container>&
operator=(typename Container::value_type&& value);

So, to be compatible with both versions of the C ++ standard, define both value_typeand const_reference_type.

In both GCC 4.4.6 and 4.5.1, the definition is operator=identical to ( libstdc++-v3/include/bits/stl_iterator.h):

  back_insert_iterator&
  operator=(typename _Container::const_reference __value)
  {
    container->push_back(__value);
    return *this;
  }

and I get the same error with both compilers, you might need to double check if you are using the correct version of the compiler.

+6
source

, const_reference, , , GCC 4.4 lvalue std::back_insert_iterator :

template<class Container>
back_insert_iterator<Container>& 
back_insert_iterator<Container>::operator= 
                  (typename Container::const_reference value);

, const_reference , std::back_insert_iterator.

GCC 4.5 lvalue

template<class Container>
back_insert_iterator<Container>&
back_insert_iterator<Container>::operator=
                 (const typename Container::value_type& value);

++ 11. GCC 4.5, , value_type.

+1

All Articles