I have a class having an element which contains a raw pointer of another object as following. Note that the example I simplified from my actual work may probably work, but I am trying to get conceptual mistake if I am doing here, because in the perfectly same structure and scenario I am getting segmentation fault error.
/*This doesn't have a raw pointer of another object*/
class H1 {
private:
int x, y;
public:
constructors;
copy_constructor;
}
/*This has a h1_ptr element which is a raw pointer of H1*/
class G1 {
private:
int count;
H1* h1_ptr;
public:
G1(int c, H1* lst){
count = 0;
h1_ptr = lst;
}
G1(const G1& g) {
count = g.count;
h1_ptr = g.h1_ptr;
}
G1& operator=(const G1& g)
{
count = g.count;
h1_ptr = g.h1_ptr;
}
}
/*The class that I create unique_ptr from*/
class H3 {
private:
H1 h1, h2;
G1 g1;
public:
H3(H1 _h1, H1 _h2, G1 _g1){
h1 = _h1; h2 = _h2; g1 = _g1;
}
}
I create a unique_ptr
from the class H3
in a function and return it to another function:
unique_ptr<H3> create_ptr(){
H1 h1(5, 10);
H1 h2(50, 100);
H1* h1_lst = new H1[20];
H1 ls;
for (int i=0;i<20;i++)
{
H1 ls(i, i*2);
h1_lst[i] = ls;
}
G1 g1(200, h1_lst);
unique_ptr<H3> p_h3(new H3(h1, h2, g1));
return p_h3;
}
int main(){
unique_ptr<H3> p_h3 = create_ptr();
H3* h_3 = p_h3.get();//to get the raw pointer
G1 g1(h_3->g1);//corrected
H1* h1_lst = g1.h1_ptr;
for (int i=0;i< 5; i++){
//I just want 5 of them even if there is more
H1 ls = h1_lst[i];
cout << ls.x << ":" << ls.y << endl;
}
return 0;
}
This will just write 1 or 2 lines, then it will crash with segmentation fault. If I didn't return the unique pointer, but get the raw pointer and write the result in the create_ptr
function instead, it would work perfectly fine.