0

I have a following code:

std::map<size_t,Cell&> m_cellMap;

when Cell is defined as follows:

class Cell
    {
      public:
        Cell(int x = 0,int y = 0) : m_x(x),m_y(y) { }
      private:
        int m_x;
        int m_y;
        /// class members and methods
    };

I can`t compile below code:

Cell c;
m_cellMap[0] = c;

Getting the error : error C2101: '&' on constant What is wrong ?How can it be fixed?

Thanks

YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • References aren't default constructible or assignable. These operations are required for the mapped_type in the operation you show. – juanchopanza Mar 12 '13 at 21:01

3 Answers3

9

It is not possible to hold references in standard containers, use pointers instead:

std::map<size_t,Cell*> m_cellMap;

Cell c;
m_cellMap[0] = &c;
Mankarse
  • 39,818
  • 11
  • 97
  • 141
6

You cannot make a std::map to references. A reference doesn't have the properties that a value that a std::map maps to must have.

Try creating a std::map<size_t, Cell*>, and doing m_cellMap[0] = &c;

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
0

If you do not want to deal with raw pointers (and you really don't want to), then you can use std::reference_wrapper instead.

std::map<size_t,std::reference_wrapper<Cell>> m_cellMap;

If you do that, then you need to avoid using the [] operator.

Do the following to insert into the map.

m_cellMap.insert(std::make_pair(0, c));

If you use pointers instead of references, then you need to manage the lifetime of the Cell object that you create.

Mankarse
  • 39,818
  • 11
  • 97
  • 141
Matthew T. Staebler
  • 4,756
  • 19
  • 21
  • I don't see any difference between this and a raw pointer. Both imply that something else is managing the lifetimes of the referenced objects. – Mankarse Mar 12 '13 at 21:16
  • The difference being that with the raw pointer, you are responsible for deleting the pointer when you are done with it. Using `reference_wrapper`, the object will exist as long as you need it to and will be cleaned up automatically. – Matthew T. Staebler Mar 12 '13 at 21:18
  • 2
    But I guess that is not correct with reference_wrapper. I am confusing that with the functionality of shared_ptr. With reference_wrapper, the lifetime of the object is still dependent upon the scope in which the object was created. – Matthew T. Staebler Mar 12 '13 at 21:20