简体   繁体   中英

When constructing a derived class which defines a base class member of some large type, how should I pass the value?

Suppose I have 3 classes: Base , Derived and Chunky . Derived is derived from Base , and Base has a member of type Chunky ( Chunky is large, and I don't want to copy it unless I have to).

Here is Base , assume that we cannot change it in any way (no, we can't create a constructor for it):

class Base
{
public:
  Chunky monkey;
}

Derived looks something like this:

class Derived : public Base
{
  // option 1
  Derived(Chunky const& monkey)
  {
    this->monkey = monkey;
  }

  // option 2
  Derived(Chunky monkey)
  {
    // does this do anything useful, or am I wasting my time by calling std::move?
    this->monkey = std::move(monkey);
  }
}

I like option 2 better because the intent is clearer and I don't have to create a reference value, but do we still have the benefit of std::move when monkey can't be initialised in constructor initializer list? How would you solve this problem (again assuming Base can't change)?

In case anyone wants to know, monkey in this case is an std::function, and this discussion didn't really answer my question.

Yes, there is still the benefit of move in the second case, even if the move is not in the member initializer list. But be aware that in this case move assignment is used instead of move construction, so the Chunky type needs to support that. As Chunky is std::function it is OK.

The second option seems preferable as it may avoid copy compared to the first option. In the better case it needs just two moves, but in the worse case a copy followed by a move is performed. The first option always needs a single copy.

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