-1

This following code doesn't want to compile:

#include <list>

int main()
{
  std::list<int *&> l;

  return 0;
}

It's a *& and not only a *. Why ? Ho hell why this doesn't work ? I tried to look for an answer on the internet but no way to get something relevant. Could you help please ?

Have a good day !

  • 1
    What exactly do you expect to accomplish with a list of references to pointers? – Sam Varshavchik Apr 07 '17 at 10:37
  • I already read this one, Its not the same type. Here I have a *& – Rodolphe Chartier Apr 07 '17 at 10:41
  • I wish to spare some memory with reference to pointers, its not an int in my program, its an object. – Rodolphe Chartier Apr 07 '17 at 10:42
  • 1
    Well, I have some shocking news for you: references would take exactly the same amount of memory to store as pointers. That's because a reference is just a pointer in disguise. – Sam Varshavchik Apr 07 '17 at 10:43
  • Its not an alias ? – Rodolphe Chartier Apr 07 '17 at 10:44
  • How do you expect a completely different translation unit, somewhere else in the code, know what a reference created by some other, completely unrelated class, is aliasing? C++ is not telepathic. When a reference is declared and used only within the same function, for example, which the compiler sees in its entirety, the compiler can usually work out what the reference is aliasing, and optimize away the entire pointer that the reference actually is. But, as soon as you have references flying everywhere, the compiler has no clue what they're "alias"ing, and had to use, guess what? A pointer. – Sam Varshavchik Apr 07 '17 at 10:53

1 Answers1

1

It is not allowed to use references for container type. But you can use std::reference_wrapper instead.

std::list<std::reference_wrapper<int>> l;

Or you can use pointer to pointer

 std::list<int**> l;
arturx64
  • 943
  • 4
  • 12