What are the benefits and risks, if any, of using std :: move with std :: shared_ptr

I am involved in exploring the power of C ++ 11, and as part of this, I plunge my head first into the world unique_ptrand shared_ptr.

When I started, I wrote code that I used unique_ptrexclusively, and therefore, when I was passing my variables around, I needed to do this with std::move(or so I understood).

After some effort, I realized what I really needed shared_ptrinstead of what I was doing. Quick search / replace later and my pointers were switched to general, but lazily I just left the calls move().

To my surprise, this compilation not only worked, but also worked great in my program, and I got every ounce of functionality that I expected ... especially, I was able to "move" shared_ptrfrom ObjectA to ObjectB, and both objects had access to it and could manipulate it. Fantastic.

This raised a question for me, though ... move()does the call actually do anything when I'm on shared_ptr? And if so, then what, and what are the consequences of this?

Code example

shared_ptr<Label> lblLevel(new Label());

//levelTest is shared_ptr<Label> declared in the interface of my class, undefined to this point
levelTest = lblLevel;

//Configure my label with some redacted code

//Pass the label off to a container which stores the shared_ptr in an std::list
//That std::list is iterated through in the render phase, rendering text to screen
this->guiView.AddSubview(move(lblLevel));

At this point, I can make important changes to levelTest, such as changing the text, and these changes are reflected on the screen.

, levelTest shared_ptr - , move() . . . MinGW Windows.

+4
3

- - , , 20.7.2.2.1:

22 - : *this r. r . r.get() == 0.

, , - , std::move.

:

std::shared_ptr<int> p = std::make_shared<int>(5);
std::shared_ptr<int> q = std::move(p);
assert(p.get() == nullptr);
+3

ecatmur , , .

, levelTest lblTest, . lblTest, levelTest .

lblTest, , , . shared_ptr, , (levelTest guiView) ( get ), ( use_count 2 , ).

shared_ptr , , , , shared_ptr .

+4

shared_ptr, (- ).

, shared_ptr A B, B A , A . , A B.

You can think of movement as an effective way to “steal resources” from a source of movement to a destination of movement.

+2
source

Source: https://habr.com/ru/post/1535839/


All Articles