简体   繁体   中英

Can I push a smart pointer to a list of smart pointers?

I have the following code:

class MarchingEvent
{
...
};

typedef std::list< std::shared_ptr<MarchingEvent> > Segment;

Can I do:

void myFunction(std::shared_ptr<MarchingEvent> A)
{
    Segment segment;
    segment.push_back( A ); // <- Questionable line.
}

Will my smart pointer be correctly incremented when pushing A to segment ?

Will my smart pointer be correctly incremented when pushing A to segment?

Yes. That's what std::shared_ptr is supposed to do.

Note, however, that if you don't use the object A after the call to push_back , you might want to change the last line to

segment.push_back(std::move(A));

to move-construct the element in segment instead of copying it - the copying has already been done upon entry of the function, because A is passed by value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM