通过指针传递对象并对其进行修改不会改变对象的状态

用户名

代码如下。我有一个名为book_b的数据成员,并且在函数OB :: x()中,此unordered_map获取插入的对象。在第一次插入时,键为10,并且在key = 10处插入的新对象工作正常。但是,当key = 10再次出现时,我预计将创建一个新对象并将其插入到key = 10处(将先前的对象替换为key = 10处)。但是,一旦OB :: x()返回,当我们返回OB :: y()时,就好像从未插入新对象一样。

我认为这应该起作用,因为我通过将book_b对象传递给了指向修改其状态的函数的指针?我担心我的基本理解有问题。

class OB{
    public:
        void y(O lo);
        void x(std::unordered_map<int, PL>* book, int a, long b);

    private:
        std::unordered_map<int, PL> book_b;
        std::unordered_map<int, PL> book_a;
};


void OB::y(O lo){

    //Code which obtains parameters to use in x() from lo
    int a = o.getA();
    long b = o.getB();

    //This is the data member the below function will insert an object in to
    std::unordered_map<int,PL>* book = &book_b;

    //This is the function which should be changing the state of book.
    //It works on the first call (when a new object is inserted) but on repeated calls
    //(where the object may be replaced with a new object with the same key) it acts
    //as if the new key-value pair wasnt replacing the existing key-value pair.

    x(book, a, b);

}


//Works when book is empty and we insert a new PL object, however, when I go to "overwrite"
//an existing PL object with the same key (a) it doesn't hold state once the function returns

void OB::x(std::unordered_map<int,PL>* book, int a, long b){
    PL temp;
    temp.setQuantity(b);
    book->insert(std::make_pair(a, temp));
}
juanchopanza

std::unordered_map::insert,如果一个使用相同的密钥已经存在插入一个新元素。

auto p = book->insert(std::make_pair(a, temp));
std::cout << std::boolalpha;
std::cout << "Did insert succeed? " << p.second << std::endl;

如果要更新现有元素(如果存在),请使用operator[]

(*book)[a] = temp;

注意:您不需要传递指针,除非您希望允许传递指针nullptr使用引用更简单:

void OB::x(std::unordered_map<int,PL>& book, int a, long b) { ... }

x(book_b, a, b);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章