Skip to content

Instantly share code, notes, and snippets.

@slashvar
Created October 12, 2021 11:27
Show Gist options
  • Save slashvar/e04db785c96d7d5037423043b13a8b3d to your computer and use it in GitHub Desktop.
Save slashvar/e04db785c96d7d5037423043b13a8b3d to your computer and use it in GitHub Desktop.
`const auto&` vs `const auto`
#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