The first copy is from a1
to the parameter a
of the MyClass constructor, the second one is from the parameter a
to the member var
.
If you want to reduce the number of copies, you have (at least) two options:
Pass a const reference to the constructor as mentioned by Joris:
MyClass(A const &a) : var(a) {
}
If A can be efficiently moved, take a
by value and move to the member:
MyClass(A a) : var(std::move(a)) {
}
That way, a user that does not need his A
anymore can move it into the new MyClass instance, while a user that still needs the A can pass it by value.
void useA(A &a);
void doSomethingWithM(MyClass & m);
void functionThatNeedsAAgain() {
A myImportantA;
MyClass m {myImportantA}; // copy myImportantA once
useA(myImportantA);
doSomethingWithM(m);
}
void functionThatDoesNotNeedAAgain() {
A tempA;
// no copy needed, as tempA will never be used again
MyClass m {std::move(tempA);
doSomethingWithM(m);
}
The third option would be to provide constructors from both const A&
and A&&
but I would weigh the code duplication against the benefit.
If you want to know how far this can be taken if A
happens to be std::string
and you want to cover the construction of temporary A
s, watch this excellent talk by Nicolai Josuttis.