Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,
I got a crash while adding item to a static vector in class A ;

static std::vector< pegshort > keys;

In another class, I try to insert item as follows ;

A::keys.push_back(x); // the program crashes in this code block
(x is a pegshort type variable )

When I do all steps for a non-static vector it works OK. But I need a static vector.
Could you please help about the cause of crash ?
Posted
Updated 28-Aug-14 4:17am
v3
Comments
Richard MacCutchan 28-Aug-14 10:46am    
Please show the exact details of the error, including the line of code where it occurs and the values of all variables relevant to the problem.
nv3 28-Aug-14 11:00am    
That could be caused by adding an item at a time when the keys vector has not been initialized yet. For example you might add an element from a piece of code in the constructor of another static object. Such initialization problems are quite common.
Sergey Alexandrovich Kryukov 28-Aug-14 14:20pm    
Good point. I actually cannot see other possibilities. OP is recommended to use the debugger and put a breakpoint on that line.
—SA
Philippe Mori 28-Aug-14 21:42pm    
In such case using Singleton pattern might be adequate.
nv3 29-Aug-14 3:11am    
Exactly! Thanks for the hint, Philippe.

1 solution

C++
// On-Demand Test.cpp :)

#include "pegshort.h"
#include <vector>

typedef std::vector<pegshort> vecKeys;

vecKeys& GetStaticKeys()
{
  static vecKeys s_keys;
  return s_kes;
}

class Test
{
public:
  Test()
  {
    GetStaticKeys().push_back(pegshort(3));
  }
} testIt;
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900