Shared_ptr indirection:(* a).b和a-> b之间的区别?

时间:2022-03-02 21:43:52

To my knowledge, foo->bar() is the same as (*foo).bar(), except when the arrow is overloaded in a weird way, which usually should not be done. This answer seems to concur.

据我所知,foo-> bar()与(* foo).bar()相同,除非箭头以奇怪的方式重载,通常不应该这样做。这个答案似乎是一致的。

This however seems to not be true for boost::shared_ptrs. Above are two lines of my code that yield different results in some cases:

然而,对于boost :: shared_ptrs来说,这似乎并非如此。以上是我的代码的两行,在某些情况下会产生不同的结果:

(*new_link).getRefNode()  // returns some value
new_link->getRefNode()    // returns something different...

What am I missing / not understanding here?

我在这里缺少什么/不理解?

Edit: As requested, the cout code and what gets printed. I made sure that getRefNode() does not modify the instance in any way - if I change the order of the calls, the values change with the calls, so it's not about anything that getRefNode() does internally.

编辑:根据要求,cout代码和打印的内容。我确保getRefNode()不会以任何方式修改实例 - 如果我改变调用的顺序,值会随着调用而改变,所以它不是getRefNode()内部执行的任何操作。

    std::cout << "BLink1: " << (*previous_link).getId().toStdString()
              << ", ref: " << (*previous_link).getRefNode()
              << ", nref: " << (*previous_link).getNrefNode()
              << std::endl << "Link2: " << (*new_link).getId().toStdString()
              << ", ref: " << (*new_link).getRefNode()
              << ", nref: " << (*new_link).getNrefNode() << std::endl;
    std::cout << "New link: " << new_link->getId().toStdString()
              << ", ref: " << new_link->getRefNode()
              << ", nref: " << new_link->getNrefNode() << std::endl;

BLink1: 1076889319, ref: (48.68674, 8.99122), nref: (48.68682, 8.99368)

BLink1:1076889319,ref:(48.68674,8.99122),nref:(48.68682,8.99368)

Link2: 1076570435, ref: (48.68674, 8.99122), nref: (48.68682, 8.99368)

Link2:1076570435,ref:(48.68674,8.99122),nref:(48.68682,8.99368)

New link: 1076570435, ref: (48.68669, 8.98889), nref: (48.68674, 8.99122)

新链接:1076570435,参考:(48.68669,8.98889),参考:(48.68674,8.99122)

(Highlights by me)

(我的亮点)

1 个解决方案

#1


0  

It turns out that the problem is not in the difference between (*a) and a->, but in chaining them together in the same cout. Doing cout << a->func() << b->func(); yields different results from cout << a->func(); cout <<b->func();.

事实证明,问题不在于(* a)和a->之间的区别,而是在同一个cout中将它们链接在一起。做cout << a-> func()<< b-> func();从cout << a-> func()得到不同的结果; cout << b-> func();.

I'll open a new question for that.

我会为此提出一个新问题。

#1


0  

It turns out that the problem is not in the difference between (*a) and a->, but in chaining them together in the same cout. Doing cout << a->func() << b->func(); yields different results from cout << a->func(); cout <<b->func();.

事实证明,问题不在于(* a)和a->之间的区别,而是在同一个cout中将它们链接在一起。做cout << a-> func()<< b-> func();从cout << a-> func()得到不同的结果; cout << b-> func();.

I'll open a new question for that.

我会为此提出一个新问题。