I have:
MyClass myObject1( var1, var2 );
myObject1.someMethod(); //> Changes the interal state of the object
Now at some point I want to assign to myObject1
a "clean" object of type MyClass
. Something like:
myObject1 = MyClass( otherVar1, otherVar2 );
Without using pointers (and/or unique_ptr
) is there any fast/efficient way to do it?
Point 1. Don't worry about performance until you have data from your profiler indicating that you should. Doing otherwise is called premature optimization, and it's a bad thing. Choose the simplest design first.
Point 2. In C++11, you can write a move assignment operator for MyClass
, if that makes sense in your case (hard to say without knowing the definition of MyClass
).
However, an even better idea would be to use RAII wrappers such as unique_ptr
as members of your class, and let the compiler-generated move assignment operator do a member-wise move and delegate the work to the move assignment operator of your members. Then, the move assignment operator of your unique_ptr
would take care of doing The Right Thing.
This way you would not have to bother following the Rule of Three, Rule of Five, or whatnot, you would get optimal performance, and (as a bonus) exception-safety. Avoid defining your own special member functions, and get used to follow the Rule of Zero.
As mentioned by juanchopanza in the comments, in C++03 you could provide a no-throw swap()
function - but again, that may or may not help depending on the definition of your class.