Why can't I use reference types as the value type of a container type?

For example, std::vector<int&> vec_int; this seems unacceptable in C ++. Why is this invalid?

+7
c ++ stl
source share
3 answers

Answer as per chryspi request above. As commented in other answers, you cannot use links directly, since links do not exist on their own.

However, you can use the links, but using the utility class boost::reference_wrapper<T> :

  typedef boost::reference_wrapper<int> intref; std::vector<intref> v; int i; i = 9; v.push_back (boost::ref (i)); // store &i int& j = v[0]; j = 10; //v[0].get() = 10; std::cout << i << std::endl; // prints 10 

As an example, I will give you how to directly change the element v[0] . Note that this is somewhat complicated (you must call the get() method) because instead of the actual link you get boost::reference_wrapper<T> .

For safe storage of pointers regarding memory, you can use boost::shared_ptr same way.

+3
source share

STL containers should be able to create objects with a standard constructor. You cannot do this with a link. The link is guaranteed, so it should always be initialized with the destination.

Instead, you need to use a pointer.

+9
source share

Internally, a vector<T> uses an array to store a sequence of T objects. Since links are not objects, there is no such thing as an array of links (see 8.3.2 ยง 5 in the standard), therefore reference types cannot be used to parameterize the vector template.

Maybe you need a vector of smart pointers like std::vector<boost::shared_ptr<T> > or a dedicated pointer container like boost::ptr_vector<T> .

+3
source share

All Articles