Skip to content

Instantly share code, notes, and snippets.

@elbeno
Last active February 16, 2016 03:58
Show Gist options
  • Save elbeno/126a8796300e1f5a5fa1 to your computer and use it in GitHub Desktop.
Save elbeno/126a8796300e1f5a5fa1 to your computer and use it in GitHub Desktop.
C++ auto may cause unwanted copies with getters
#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