Is it OK to inherit from the C++11 smart pointers and override the relative operators?

前端 未结 3 2071
野性不改
野性不改 2021-02-18 21:27

According to cppreference.com, std::shared_ptr provides a full set of relative operators (==, !=, <, ...), but the semantics of comparison aren\'t specified. I a

3条回答
  •  甜味超标
    2021-02-18 21:54

    It's hazardous to inherit from any class that supports assignment and copy-construction, due to the risk of cutting a derived-class instance in half by accidentally assigning it to a base-class variable. This affects most classes, and is pretty much impossible to prevent, thus requiring vigilance on the part the class's users whenever they copy instances around.

    Because of this, classes intended to function as bases usually shouldn't support copying. When copying is necessary, they should provide something like Derived* clone() const override instead.

    The problem you are trying to solve is probably best addressed by leaving things as they are and providing custom comparators when working with such pointers.

    std::vector> ii = …;
    std::sort(begin(ii), end(ii),
              [](const std::shared_ptr& a, const std::shared_ptr& b) {
                  return *a < *b;
              });
    

提交回复
热议问题