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

Yakov
  • 9,221
  • 29
  • 109
  • 199
  • 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
  • 38,538
  • 10
  • 94
  • 140
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
  • 250,370
  • 26
  • 305
  • 497
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
  • 38,538
  • 10
  • 94
  • 140
Matthew T. Staebler
  • 4,518
  • 18
  • 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