I’m creating a small program with some design patterns, and I’m trying to implement a singleton. In this singleton class I have a vector containing a File object which I defined myself.
Now, when doing the actual push_back, I get a segmentation fault. I tried removing the singleton pattern and the push_back worked great. I’ve read on a forum that the problem might be cause by the vector not being initialized yet. Is their a way that would allow me to use my vector and my singleton pattern without causing a segmentation fault?
EDIT:
header:
class FileManager
{
public:
static FileManager* GetManager();
~FileManager();
void InitManager();
void LoadAllTitle();
private:
FileManager();
static FileManager* _fileManager;
std::vector<File> _files;
};
source:
//C++ Header
#include <iostream>
//C Header
//local header
#include "filemanager.h"
#include "settings.h"
#include "defs.h"
#include "file.h"
#include "utilities.h"
FileManager* FileManager::_fileManager = NULL;
FileManager* FileManager::GetManager()
{
if( _fileManager )
{
_fileManager = new FileManager();
}
return( _fileManager );
}
FileManager::FileManager()
{
}
FileManager::~FileManager()
{
}
void FileManager::InitManager()
{
int numberOfFile = Settings::GetSettings()->NumberOfFile() + 1;
for( unsigned int i = 1; i < numberOfFile; i++ )
{
std::string path = "data/data";
path += IntToStr( i );
path += ".ndb";
File tempFile( path );
_files.push_back( tempFile ); // segmentation fault
}
printf( " Done...\n" );
}
void FileManager::LoadAllTitle()
{
int numberOfFile = Settings::GetSettings()->NumberOfFile() + 1;
std::string titles = "ALL TITLES: \n";
for( unsigned int i = 1; i < numberOfFile; i++ )
{
titles += _files[i].ReadTitle();
titles += "\n";
}
}
And here is the call I make in main.cpp
FileManager::GetManager()->InitManager();
The thing is if I place my constructor in public and do this in the main:
FileManager fm;
fm.InitManager();
this doesn’t return a segmentation fault
Your logic is backwards –
if (_fileManager)should beif (!_fileManager).