【问题标题】:Passing object by pointer and modifying it isn't changing state of the object通过指针传递对象并修改它不会改变对象的状态
【发布时间】:2013-11-23 10:25:07
【问题描述】:

代码如下。我有一个名为 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));
}

【问题讨论】:

    标签: c++ pointers c++11 pass-by-reference pass-by-pointer


    【解决方案1】:

    std::unordered_map::insert "如果容器中不包含具有等效键的元素,则将元素插入容器中。"

    改变

    book->insert(std::make_pair(a, temp));
    

    (*book)[a] = temp;
    

    还要注意,在这里通过引用而不是指针传递会更合理,并使您的代码更清晰:)

    【讨论】:

    • 我只是通过引用传递您在上面的代码中看不到的非常具体的目的:)
    【解决方案2】:

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

    【讨论】:

    • 注意,为了获得最大的性能和最大的丑陋,你可以这样做:auto p = book-&gt;insert(std::make_pair(a, temp)); if (!p.second) { p.first-&gt;second = temp; }
    • 我只是通过引用传递您在上面的代码中看不到的非常具体的目的:)
    猜你喜欢
    • 2017-10-21
    • 2020-08-11
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多