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

时间:2013-11-11 15:01:56

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

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

2 个答案:

答案 0 :(得分:3)

如果已存在具有相同密钥的新元素,则

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

答案 1 :(得分:1)

std::unordered_map::insert “将元素插入容器中,如果容器尚未包含具有等效键的元素。”

更改

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

(*book)[a] = temp;

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

相关问题