Hi,
When I initialise then access the g_spMyLog
shared pointer, from within the CSingleton::CreateLog
member function, it works ok. Accessing the SP from the static member function of CSingleton::Create()
causes an access violation
in the original project and an abort in this sample project displayed below.
In the original project I think the object is going out of scope somewhere but I don't know where. The factory function is created within a DLL as return (static_cast<void*>(new CMyLog));
which is then static_cast
to a CMylog*
straight into a shared_ptr like this: g_spMyLog.reset(static_cast<CMyLog*>(CreateVoidObj(is_Binary)));
but that's not included here.
// File: CSingleton.h
#pragma once
#include "CMyLog.h"
#include <string>
#include <boost\shared_ptr.hpp>
#include <boost\make_shared.hpp>
#define BOOSTSP boost::shared_ptr
#define BOOSTMKSHD boost::make_shared
class CSingleton
{
public:
static void Create(void);
static void Destroy(void);
~CSingleton(void) {}
BOOSTSP<CMyLog> CreateLog(bool is_Binary);
protected:
CSingleton(void) {} // Hidden constructor
private:
// PRIVATE SEMANTICS
CSingleton(const CSingleton& other) {} // Copy constructor
friend void swap(CSingleton& first, CSingleton& second) {} // Swap implementation
CSingleton& operator=(CSingleton other) {} // Assignment operator
CSingleton(CSingleton&& other) {} // Move constructor
};
extern BOOSTSP<CSingleton> g_spSingleton;
extern BOOSTSP<CMyLog> g_spLog;
// File: CSingleton.cpp
#include "CSingleton.h"
#include "CMyLog.h"
BOOSTSP<CSingleton> g_spSingleton = nullptr;
BOOSTSP<CMyLog> g_spLog = nullptr;
void Create(void);
void Destroy(void);
void CSingleton::Create(void)
{
if (!g_spSingleton)
{
// Create engine and start log
g_spSingleton.reset(new CSingleton());
g_spLog = g_spSingleton->CreateLog(false);
//
int i = g_spLog->Get(); // << Abort has been called ERROR
g_spLog->Set(245);
i = g_spLog->Get();
}
} // Create
BOOSTSP<CMyLog> CSingleton::CreateLog(bool is_Binary)
{
static BOOSTSP<CMyLog> sp; // Ignore this.
g_spLog = BOOSTSP<CMyLog>(new CMyLog());
g_spLog->Set(1234); // <== This in the original works (here only)
int i = g_spLog->Get();
return sp;
} // CreateLog
void CSingleton::Destroy(void)
{
g_spSingleton.reset();
g_spLog.reset();
} // Destroy
// File: CMyLog.h
#pragma once
class CMyLog
{
public:
CMyLog(void) {}
~CMyLog(void) {}
void Set(int i) { m_i = i; }
int Get(void) { return m_i; }
int m_i;
private:
// etc...
};
// File: main.cpp
#include "CSingleton.h"
int main(void)
{
CSingleton::Create();
return 0;
}
Muchas gracias to anyone who can help.