Created
October 5, 2022 08:25
-
-
Save nthery/b26f1e995ad0e66c3daa6d6293ac951f to your computer and use it in GitHub Desktop.
Show how to use ref qualifiers to prevent dangling references to member variable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Show how to use ref qualifiers to prevent dangling references to member variables. | |
struct S { | |
const int& f() const& { return n_;} | |
const int& h() & { return n_; } | |
const int& g() && { return n_; } | |
const int& l() const & { return n_; } | |
const int& l() && = delete; | |
int n_ = 0; | |
}; | |
int main() { | |
S s; | |
const S ks; | |
// Problematic because callable on both lvalues and rvalues. | |
// Callable on rvalues because const lvalue refs accept temporaries (and extend their lifetime). | |
s.f(); | |
ks.f(); | |
S().f(); // returned reference dangles | |
// Safe because callables on lvalues only. | |
s.h(); | |
// does not compile (usual rules about const vs non-const member functions) | |
// ks.h(); | |
// does not compile because non-const lvalue ref do not bind to temporaries | |
// S().h(); | |
// Problematic because callable on rvalue only. | |
// does not compile because rvalue ref does not bind to lvalue | |
// s.g(); | |
// ks.g(); | |
S().g(); | |
// Safe because callable on lvalue only. | |
s.l(); | |
ks.l(); | |
// does not compile because overload deleted | |
// S().l(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment