C++/Modern C++(11, 14, 17, 20)
[C++11] ref-qualified member functions(참조 한정 멤버 함수)
deulee
2023. 8. 23. 19:39
C++11에 도입된 'ref-qualified member functions(참조 한정 멤버 함수)'은 멤버 함수의 호출 가능한 객체에 대한 제한을 나타내는 기능이다.
즉, 멤버 함수가 'lvalue'인지 'rvalue'인지에 따라 다른 버전의 멤버 함수를 호출할 수 있다.
이는 'Move Semantics'와 관련이 있으며, '객체의 임시 복사를 줄이고' 효율적인 이동을 촉진하는 데 사용된다.
멤버 함수는 이제 `*this`가 lvalue 또는 rvalue에 따라 한정될 수 있다.
struct Bar {
// ...
};
struct Foo {
Bar getBar() & { return bar; }
Bar getBar() const& { return bar; }
Bar getBar() && { return std::move(bar); }
private:
Bar bar;
};
Foo foo{};
Bar bar = foo.getBar(); // calls `Bar getBar() &`
const Foo foo2{};
Bar bar2 = foo2.getBar(); // calls `Bar Foo::getBar() const&`
Foo{}.getBar(); // calls `Bar Foo::getBar() &&`
std::move(foo).getBar(); // calls `Bar Foo::getBar() &&`
std::move(foo2).getBar(); // calls `Bar Foo::getBar() const&&`