Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static const int as map subscript

Tags:

c++

I ran into a strange issue. Considering this example:

class Foo
{
  static const int Bar = 5;

public:
  Foo()
  {
    _map[Bar] = "some characters";
  }

  ~Foo() {}

private:
  std::map<int, std::string> _map;
};

int main()
{
  Foo a;

  return (0);
}

I get this error (compiling with g++ 4.7.2):

/tmp/ccLy806T.o: In function `Foo::Foo()':
Main.cpp:(.text._ZN3FooC2Ev[_ZN3FooC5Ev]+0x1e): undefined reference to `Foo::Bar'

Now, if I make a static_cast on Bar, it works:

Foo()
{
  int i = Bar; //works
  _map[static_cast<int>(Bar)] = "some characters"; //works
}

This error only appears when using Bar as map subscript in the constructor. Writing _map[Bar] = "some characters"; in an other function in the Foo class doesn't produce any error.

That's really strange for me, but I expect that someone here has an answer.

So, what am I doing wrong ?

like image 653
Etienne Fesser Avatar asked Jan 27 '26 03:01

Etienne Fesser


1 Answers

That's because map::operator[] takes its key as a int const&. It wants the address of the thing you're passing into it. When you do:

_map[static_cast<int>(Bar)]

you're creating a temporary, and passing in the address to that temporary, which is fine. But when you're doing:

_map[Bar]

Bar doesn't actually have memory storage. You need to provide it via:

class Foo {
    ....
};

const int Foo::Bar;
like image 111
Barry Avatar answered Jan 29 '26 18:01

Barry