상세 컨텐츠

본문 제목

[C++11] ref-qualified member functions(참조 한정 멤버 함수)

C++/Modern C++(11, 14, 17, 20)

by 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&&`

 

'C++ > Modern C++(11, 14, 17, 20)' 카테고리의 다른 글

[C++11] Non-static data member initializers  (0) 2023.08.24
[C++11] Right angle brackets  (0) 2023.08.23
[C++11] Trailing return types  (0) 2023.08.23
[C++11] Noexcept 지정자  (0) 2023.08.23
[C++11] char32_t & char16_t  (0) 2023.08.23

관련글 더보기