-1

The question comes from the code below:

vector<int &> one;  //compile failed

I am confused why the code does not compile.

pmr
  • 58,701
  • 10
  • 113
  • 156
Kevin Wang
  • 135
  • 1
  • 8
  • 1
    You can't put references in containers. Use [`std::reference_wrapper`](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper). – T.C. Aug 12 '14 at 02:29
  • 1
    References are non-copyable and non-movable. – chris Aug 12 '14 at 02:30

2 Answers2

5

You can't have a vector of references directly.

However you can use std::reference_wrapper to achieve the result you seek.

  • Thank you for your answer. When the IDE(VS2008) tells me the code compile failed, Then I know "I can't have a vector of references directly", which is your answer also. I want to know the underlying reasons. Thank you. – Kevin Wang Aug 12 '14 at 02:35
  • 3
    Is "because the standard says so" good enough? "Containers are objects that store other objects." §23.2.1 [container.requirements.general] References are not objects. – Robert Allan Hennigan Leahy Aug 12 '14 at 02:37
  • Thank you. But a pointer is not a object, too. Could you help me? – Kevin Wang Aug 12 '14 at 04:02
  • 1
    A pointer is, indeed, an object. "An object is a region of storage." §1.8 [intro.object]. References are not objects, therefore, because "[i]t is unspecified whether or not a reference requires storage" §8.3.2 [dcl.ref]. – Robert Allan Hennigan Leahy Aug 12 '14 at 04:12
  • You are so smart, and hank you for your patience. And I get it. Thank you again. In addition, Could you send me a c++ standard docs? or a internet link? – Kevin Wang Aug 12 '14 at 04:20
  • While the official, ISO standard documents require payment to access, N3337 (which was, I believe, the first draft released after C++11 was accepted, and has only very minor changes) can be found [here](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) – Robert Allan Hennigan Leahy Aug 12 '14 at 04:21
  • OK, I have download from the website you give me. Thank you. Your are so friendly and smart. Thank you. – Kevin Wang Aug 12 '14 at 04:26
0

Possible duplicate of Why can't I make a vector of references? (I don't currently have the rep to flag it).

STL containers must hold types that are assignable, and references are not assignable.

Community
  • 1
  • 1
depth1st
  • 16
  • 5