简体   繁体   中英

Little problem with pointer to object in a vector in c++

Consider the following code:

class test {
    public:
    int n;
    test(int n) : n(n) {}
};

int main() {
    vector<test> v;
    test one(1), two(2);
    v.push_back(one);
    v.push_back(two);
    // obviously doesn't work since a copy of the object is stored in 
    //the vector ==> different memory addess
    test* p1 = &one;

   // also doesn't work properly since when the object gets erased,
   //this pointer is pointing to a different object
    test* p2 = &v[0]; 

    v.erase(v.begin());
    // prints 2 since object two was copied to the place of object one
    cout << p2->n << endl; 
    return 0;
}

I want a pointer that points to a specific object in a vector and, when earring this object the pointer should also get deleted or point to null or something like that. Also when I have a pointer to an object at position 3 of a vector, I want this pointer to point, after removing eg object 1, to position 2 since object 3 "moved" one position to the left. Is something like this realisable or should I try a different approach? I just started learning C++ so I'm not very familiar to any advance concepts.

As it was said, you should use std::shared_ptr with std::weak_ptr. Below is a rewrite of your code with modern approach:

#include <iostream>
#include <memory>
#include <vector>

class test {
    public:
    int n;
    test(int n) : n(n) {}
};

int main() {
    std::vector<std::shared_ptr<test>> v;
    std::shared_ptr one = std::make_shared<test>(1);
    std::shared_ptr two = std::make_shared<test>(2);
    v.push_back(one);
    v.push_back(two);

    std::weak_ptr<test> p1 = one;
    std::weak_ptr<test> p2 = v[0]; 
    
    // prints 1 two times
    if (auto sp = p1.lock()) {
        std::cout << sp->n << std::endl; 
    }
    if (auto sp = p2.lock()) {
        std::cout << sp->n << std::endl; 
    }
    
    // delete all references to one
    v.erase(v.begin());
    one = nullptr;
 
    // nothing gets printed
    if (auto sp = p1.lock()) {
        std::cout << sp->n << std::endl; 
    }
    if (auto sp = p2.lock()) {
        std::cout << sp->n << std::endl; 
    }
    return 0;
}

https://coliru.stacked-crooked.com/a/00b2072bb8cd73ad

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