Last active
February 16, 2016 03:58
-
-
Save elbeno/126a8796300e1f5a5fa1 to your computer and use it in GitHub Desktop.
C++ auto may cause unwanted copies with getters
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
#include <iostream> | |
#include <string> | |
#include <type_traits> | |
using namespace std; | |
struct Foo | |
{ | |
Foo() {} | |
Foo(const Foo&) | |
{ | |
cout << "Copied a Foo" << endl; | |
} | |
}; | |
struct Bar | |
{ | |
const Foo& GetFoo() const { return m_foo; } | |
private: | |
Foo m_foo; | |
}; | |
int main(void) | |
{ | |
Bar b; | |
cout << "Before auto" << endl; | |
auto f = b.GetFoo(); | |
static_assert(is_same<decltype(f), Foo>::value, "f is a Foo"); | |
cout << "After auto" << endl; | |
cout << "Before const auto&" << endl; | |
const auto& f_cr = b.GetFoo(); | |
static_assert(is_same<decltype(f_cr), const Foo&>::value, "f_cr is a const Foo&"); | |
cout << "After const auto&" << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment