I try to create two classes, Volume and Slice, and create a method in Volume so it can return part of its data as a Slice object. I want the two objects to share the memory to change any of them will change the same data. Currently, I have:
#include <complex>
using namespace std;
class Slice{
public:
Slice(unsigned long Nx,unsigned long Ny){ //Contructor
nx = Nx;
ny = Ny;
data = new complex<double>[Nx*Ny];
}
Slice(unsigned long Nx,unsigned long Ny,complex<double>* inputDataPtr){ //Contructor
nx = Nx;
ny = Ny;
data = inputDataPtr;
}
Slice(const Slice& inputObj){ // Copy contructor
nx = inputObj.nx;
ny = inputObj.ny;
data = inputObj.data;
}
~Slice(){ //destructor
delete data;
}
private:
// DATA:
unsigned long nx;
unsigned long ny;
complex<double>* data;
};
class Volume{
public:
Volume(unsigned long Nx,unsigned long Ny,unsigned long Nz){ //Contructor
nx = Nx;
ny = Ny;
nz = Nz;
data = new complex<double>[Nx*Ny*Nz];
}
~Volume(){ //destructor
delete data;
}
const Slice& get_slice(unsigned long zindex){
return Slice(nx,ny, &(data[zindex*nx*ny]));
}
private:
// DATA:
unsigned long nx;
unsigned long ny;
unsigned long nz;
complex<double>* data;
};
int main(){
unsigned long Nx = 1;
unsigned long Ny = 2;
unsigned long Nz = 3;
Volume testVolume(Nx,Ny,Nz);
/* initialise data in testVolume */
Slice slice = testVolume.get_slice(1);
return 0;
}
I also need to be able to create individual slices that are not related to the volume, so slice class has to allocate its own pointer as well.
When I run this, it says*** free(): invalid pointer: 0x0000000000ff1180 ***
I think the problem is when I call the get_slice method of the testVolume, the code will destroy the temporary slice object in the return, so it tries to free a non-existing pointer and cause problems.
How do I avoid this? After a bit of search, I probably need a smart pointer shared_ptr? How do I incorporate it?
Thank you.