简体   繁体   中英

Return type for *this in a builder-class method - lvalue vs rvalue refence

Suppose I have a "builder" class B which builds a class C , and looks somewhat like the following:

class B {
public:
  // ...
  B& set_foo(Foo a_foo) { foo_ = std::move(a_foo); return *this; }
  C build() const { /* ... */ }
};

This is all nice and good ... until I think about what happens when my B instance is a temporary. How should I design B to work also as temporary/rvalue, not just as an lvalue?

  • Should I write a set_foo() && variant, returning a B&& ? That would mean replicating lots of methods, and well, DRY .
  • Should I just return B&& to begin with?
  • Should I do something else?

If you happen to be using C++23, there's a feature calleddeducing this , which would allow you to perfectly forward *this , even as a return type.

class B {
public:
  // ...

  template< typename Self >
  decltype(auto) set_foo(this Self&& self, Foo a_foo)
//                       ^^^^^^^^^^^^^^^^ "this" can be specified as
//                                        a forwarding reference!
  {
      self.foo_ = std::move(a_foo);
      return std::forward<Self>(self);
  }

  C build() const { /* ... */ }
};

In this code, the return type will match whether *this is an l-value, r-value, const and/or volatile .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM