提问者:小点点

C++中向量对象指针的小问题


请考虑以下代码:

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;
}

我想要一个指针,指向一个特定的对象,在一个向量,当耳环这个对象,指针也应该被删除,或指向空或类似的东西。同样,当我有一个指向矢量位置3的对象的指针时,我希望这个指针在移除例如对象1之后指向位置2,因为对象3向左“移动”了一个位置。这样的事情是可以实现的还是我应该尝试一种不同的方法?我刚开始学习C++所以我对任何高级概念都不是很熟悉。


共1个答案

匿名用户

如前所述,您应该将std::shared_ptr与std::weak_ptr一起使用。下面是用现代方法重写的代码:

#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

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|向量|对象|指针|小问题)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?