Was sind die Unterschiede zwischen den folgenden zwei Implementierungen für den Zugriff auf eine private Konstante Klasse Mitglied?Auto-Abzug für Const-Klasse Mitglied
// Auto& (compile ok)
class Foo {
private:
const int _foo;
public:
Foo(const int& in) : _foo(in) {}
auto& foo() { return _foo; }
}
// Explicit type (compiler error)
class Foo {
private:
const int _foo;
public:
Foo(const int& in) : _foo(in) {}
int& foo() { return _foo; }
}
Mit auto
die Compiler beschweren sich nicht, aber die explizite int
Typdeklaration in der Tat gibt Compiler-Fehler (die die Konstantheit zurückzuführen ist). In diesem Fall, was ist auto
abgeleitet?
Hinweis: Stellen Sie sicher, dass Sie wissen, was Sie tun w.r.t. Semantik bei der Verwendung von Const-Referenzen. Siehe [int vs const int &] (http://stackoverflow.com/a/4705871/211160). Und beachte, dass es durchaus langsamer sein könnte, als einen int zurückzugeben. – HostileFork