简体   繁体   中英

Swap in C++ - best practice

I have a class having the following structure:

class MyClass {
std::string _myField;
constructor
//copy constructor
//assignment operator
}

When I create the object I would like to swap the string instead of copying it. Still, this is against best practices.

Therefore, is there any other better solution to achieve this (movement operator)? Not even if I use a setXXX and I use swap is not a best decision.

I want to achieve the best performances.

Thank you for your help!

For best performance, pass the std::string by value in the constructor and initialize the member variable using the move constructor:

MyClass (std::string s) : _myField (std::move(s)) { /* ... */ }

Want Speed? Pass by Value

PS. The general advice (pattern?) seems to be to always pass by value the sink arguments.

I want to achieve the best performances.

This is not possible when using swap :

swap requires two operands - which obviously is the member variable and the parameter from the c-tor. That is, your member variable needs to be initialized before swap is called. This will invoke a few instructions which are strictly not necessary.

In order to construct your instance with a string argument, use @chill's approach. ;)

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