Created
October 12, 2021 11:27
-
-
Save slashvar/e04db785c96d7d5037423043b13a8b3d to your computer and use it in GitHub Desktop.
`const auto&` vs `const auto`
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
#include <iostream> | |
#include <string> | |
#include <type_traits> | |
struct Foo | |
{ | |
std::string content; | |
const std::string& get() const | |
{ | |
return content; | |
} | |
}; | |
int main() | |
{ | |
Foo foo { "foo" }; | |
{ | |
/* | |
* str is a value | |
*/ | |
const auto str = foo.get(); | |
static_assert(std::is_same_v<decltype(str), std::remove_reference_t<decltype(str)>>); | |
} | |
{ | |
/* | |
* str is a reference | |
*/ | |
const auto& str = foo.get(); | |
static_assert( | |
not std::is_same_v<decltype(str), std::remove_reference_t<decltype(str)>>); | |
} | |
{ | |
/* | |
* str is a reference | |
*/ | |
auto&& str = foo.get(); | |
static_assert( | |
not std::is_same_v<decltype(str), std::remove_reference_t<decltype(str)>>); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment