简体   繁体   中英

loosing pointers on vector of struct instances, with pointers in the struct

Not sure if the title is right or not, but here it goes:

If I have for example the following structure:

struct strA{
    int x;

    strA(int x);
}

strA::strA(int x){
    this->x = x;
}

And another structure that uses a pointer to the previous one:

#include strA

struct strB{
    int y;
    strA *var_strA;

    strB(int y);
    ~strB(){
        delete var_strA;
    }
};

strB::strB(int y){
    this->y = y;
    var_strA = new strA(123);
}

Then if I do from the main aplication a vector of strB items:

std::vector<strB> vectB;

main(){
    strB *itemB = new strB(456);
    vectB.push_back(*itemB);
    delete itemB;

    //more code
}

If I try to access the var_strA on the item in the vector, is empty. And also, I get an error when by deleting the item on the vector, since the destructor tries to delete var_strA again.

Comming from Java... I'm really getting lost with the damn pointers.

thanks in advance

You need a copy constructor and a copy assignment operator on that pointer-holding type, ie follow the rule of three . Here's a great resource here on SO: What is The Rule of Three?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM