通过指针传递对象并对其进行修改不会更改对象的状态
Passing object by pointer and modifying it isn't changing state of the object
代码如下。我有一个名为 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));
}
如果已经存在具有相同键的元素,则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);
std::unordered_map::insert
" 如果容器尚未包含具有等效键的元素,则将元素插入容器中。
改变
book->insert(std::make_pair(a, temp));
自
(*book)[a] = temp;
还要注意的是,在这里通过引用而不是指针传递会更合理,并使你的代码更干净:)
相关文章:
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 使用可变允许修改unordered_set中的对象
- 未定义的对象(〔basic.life〕/8):为什么允许引用重新绑定(和常量修改)
- 如何修改函数中的对象?
- 结构对象的指针成员在传递给函数时被修改
- 修改多线程应用程序中的对象
- 通过引用在矢量中放置和修改对象
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- 如何修复对象在释放后可能修改的malloc错误
- const 方法使用引用修改对象
- C++ API:修改内部对象
- C++ 在其自己的类中创建对象的修改副本
- 打印/修改类对象的特定成员变量,其类定义列表 (STL) 包含的元素类型
- 我可以制作一个对象方法,如果单独调用,它将自行修改,但如果在复制初始化期间调用,则会返回一个新对象?
- 在C 向量中修改对象值的麻烦
- 使用基对象修改/访问派生类的信息的有问题的设计
- 对象修改通知
- 从c++中GUI中创建的对象修改GUI
- 将等待多个对象修改*多个*对象的状态