I have written some class that moves heap allocated stuff to stack (hopefully :) ). This calss is singleton because only this class should be responsible for holding and managing part of stack. My question is: Is my code correct? Code is correct in the sense of programming (no compile errors, no memory errors and leaks (checked by valgrind)). But does the code really moves heap to stack? Here's the code:
stack.hpp:
class CStack{
public:
void* getAlloc(long);
static CStack* Instance();
private:
static bool _data[5*sizeof(double)];
static CStack* m_pInstance;
CStack(){};
CStack(const CStack&);
CStack& operator=(const CStack&);
};
stack.cpp:
#include <iostream>
#include "stack.hpp"
CStack* CStack::m_pInstance = 0;
bool CStack::_data[ 5*sizeof(double) ] = { 1 };
CStack* CStack::Instance(){
if (!m_pInstance)
m_pInstance = new CStack;
return m_pInstance;
}
void* CStack::getAlloc(long size){
std::cout << " CStack::getAlloc, " << _data << std::endl;
_pos+=size;
return &_data[0];
}
store.hpp
class CStore{
public:
CStore();
double* myAddr();
void toStack();
void out();
~CStore();
private:
double *_data;
bool _stack;
};
store.cpp:
#include <iostream>
#include <cstring>
#include "store.hpp"
#include "stack.hpp"
CStore::CStore(){
_data = new double[4];
_data[0] = 0.1;
_data[1] = 1.1;
_data[2] = 2.1;
_data[3] = 3.1;
_stack = 0;
}
double* CStore::myAddr(){ return _data; }
void CStore::toStack(){
double *tmp;
tmp = (double*)CStack::Instance() -> getAlloc(4*sizeof(double));
memcpy(tmp, _data, 4*sizeof(double));
delete [] _data;
_data = tmp;
_stack = 1;
}
CStore::~CStore(){
if (!_stack)
delete [] _data;
}
void CStore::out(){
std::cout << _data[0] << " " << _data[1] << " " << _data[2] << " " << _data[3] << std::endl;
}
main.cpp:
#include <iostream>
#include "stack.hpp"
#include "store.hpp"
using namespace std;
int main(){
CStack::Instance();
CStore a;
double stack;
cout << &stack << endl;
cout << "Adresa a " << a.myAddr() << endl;
a.out();
a.toStack();
cout << "Adresa a " << a.myAddr() << endl;
a.out();
return 0;
}
CStack* CStack::Instance(){ if (!m_pInstance) m_pInstance = new CStack; return m_pInstance;}
implies that your object lives on the heap (see the non-placementnew
?). – dmckee --- ex-moderator kitten