Last active
May 16, 2020 03:00
-
-
Save kjelloh/c5651c03973f5eae69175b7e81487703 to your computer and use it in GitHub Desktop.
C++ - Can't pass reference to reference (value assign is implied)
This file contains hidden or 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
| struct foo { | |
| foo& operator=(const foo& other) = delete; // foo is not copy-assignable | |
| }; | |
| void bar() { | |
| foo f1; | |
| foo& r1 = f1; // Ok. r1 is reference to f1. | |
| foo& r2 = r1; // ok. r2 is refernce to r1 which is semanticly the value f1. | |
| r2 = r1; // Error. Semantics implies value assign (although both sides are references) and foo instance f1 is not assignable. | |
| // Pass refernce round with http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper | |
| std::reference_wrapper<foo> rw1 = f1; // Ok. rw1 models a foo reference to f1. | |
| std::reference_wrapper<foo> rw2 = rw1; // ok. rw2 models a foo refernce with the same value as rw1 (refernce to same value f1) | |
| rw2 = rw1; // Ok. The refernce held by rw1 is passed to rw2 (value f1 not mutated) | |
| r2 = rw2; // Error. r2 is semanticly alias for value refernced by r1 which is f1 (assign to f1 attemted) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment