0

How can I store const references or addresses to const someType& objects?

#include<iostream>
#include<list>

const int &foo( int& a) 
{
   return a;
}

int main()
{
    int a = 5;
    const int& p = foo(a);

    std::list<const int&> _list;
    _list.push_back(p);

    return 0;
}
underscore_d
  • 6,309
  • 3
  • 38
  • 64
  • What is the exact problem you're facing? – Neo Oct 25 '17 at 09:40
  • When using std containers - the containers must be able to move the objects around. This means that you can not have containers of references. Const or otherwise. – UKMonkey Oct 25 '17 at 09:41
  • the stored object should meet the requirements of `Assignable`. Since reference are initialized only once at declaration, you can have them in any containers . – P0W Oct 25 '17 at 09:44
  • if you need reference-like objects in a container, `std::reference_wrapper` might be for you – sp2danny Oct 25 '17 at 09:44
  • 1
    Possible duplicate of [STL containers with reference to objects](https://stackoverflow.com/questions/7707842/stl-containers-with-reference-to-objects) – underscore_d Oct 25 '17 at 09:50
  • or https://stackoverflow.com/questions/922360/why-cant-i-make-a-vector-of-references or any of the many other threads you could have found if you had searched first. Also, nowhere does your example actually try to form a pointer to a reference - not that doing so is valid anyway. – underscore_d Oct 25 '17 at 09:50
  • http://coliru.stacked-crooked.com/a/7559f198968f987b – sp2danny Oct 25 '17 at 09:53

2 Answers2

3

Your code doesn't compile. The problem is here:

std::list<const int&> _list;

When you declare a std::list<T>. T must meet the requirements of CopyAssignable and CopyConstructible. But neither a const nor a reference is assignable.


Apart from your problem, solutions suggesting std::reference_wrapper are not good in my opinion. Since when an object gets deleted, its reference inside that list will dangle. The best idea would be using smart pointers.

frogatto
  • 28,539
  • 11
  • 83
  • 129
  • 1
    Nice remark about using `std::reference_wrapper`, definitely something to keep in mind! – AVH Oct 25 '17 at 13:45
1

As commented by UKMonkey you can not store constant references directly in the std containers. However, there's std::cref which can be stored in such containers and wraps a constant reference. Note that you need C++11 for it.

Edit: Do heed Hi I'm Frogatto's warning about using this though. Unless you have a very compelling reason to use std::cref, it's probably better to stick to the alternative he mentions (smart pointers).

AVH
  • 11,349
  • 4
  • 34
  • 43