Soll ich in C ++ 11 immer noch const-Objekte zurückgeben? [Duplikat]
Mögliche Duplikate:
Soll ich const-Objekte zurückgeben?
(Der ursprüngliche Titel dieser Frage lautete:int foo () oder const int foo ()? erkläre, warum ich es verpasst habe.)
Effektives C ++, Punkt 3: Verwenden Sie, wann immer möglich, const. Insbesondere wird das Zurückgeben von const-Objekten gefördert, um eine unbeabsichtigte Zuweisung zu vermeidenif (a*b = c) {
. Ich finde es ein bisschen paranoid, trotzdem habe ich diesen Rat befolgt.
Es scheint mir, dass das Zurückgeben von const-Objekten die Leistung in C ++ 11 beeinträchtigen kann.
#include <iostream>
using namespace std;
class C {
public:
C() : v(nullptr) { }
C& operator=(const C& other) {
cout << "copy" << endl;
// copy contents of v[]
return *this;
}
C& operator=(C&& other) {
cout << "move" << endl;
v = other.v, other.v = nullptr;
return *this;
}
private:
int* v;
};
const C const_is_returned() { return C(); }
C nonconst_is_returned() { return C(); }
int main(int argc, char* argv[]) {
C c;
c = const_is_returned();
c = nonconst_is_returned();
return 0;
}
Dies druckt:
copy
move
Implementiere ich die Verschiebungszuweisung richtig? Oder sollte ich in C ++ 11 keine const-Objekte mehr zurückgeben?