Home > Back-end >  Sharedptr reference counting
Sharedptr reference counting

Time:10-24

# include & lt; iostream>
# include
# include
using namespace std;


Int main ()
{
Auto p=make_shared & lt; Int> (42);//! Pointing to the object is only a reference, p
Cout & lt; Auto q=make_shared & lt; Int> (56);//! A reference point to the object only q,
Cout & lt;
Cout & lt; <"-- -- -- -- -- -- -- -- -- afterAssin -- -- -- -- --" & lt; P=q;//! P released after the original reference object assignment, p and q q reference objects have two references,
Cout & lt; <* p & lt; <"==" & lt; <* q & lt; Cout & lt;
Cout & lt; }

Output:
1
1
-- -- -- -- -- -- -- -- -- afterAssin -- -
56==56
2
2
Please press any key to continue...

Question: why is the final output is 2 instead of 0

CodePudding user response:

Found the reason, p=q, q assigned to p, p, q point to the same reference, so it is 2

CodePudding user response:

Right on the second floor
  • Related