Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

stl - Extending the C++ Standard Library by inheritance?

It is a commonly held belief that the the C++ Standard library is not generally intended to be extended using inheritance. Certainly, I (and others) have criticised people who suggest deriving from classes such as std::vector. However, this question: c++ exceptions, can what() be NULL? made me realise that there is at least one part of the Standard Library that is intended to be so extended - std::exception.

So, my question has two parts:

  1. Are there any other Standard Library classes which are intended to be derived from?

  2. If one does derive from a Standard Library class such as std::exception, is one bound by the interface described in the ISO Standard? For example, would a program which used an exception class who's what() member function did not return a NTBS (say it returned a null pointer) be standard conforming?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Good nice question. I really wish that the Standard was a little more explicit about what the intended usage is. Maybe there should be a C++ Rationale document that sits alongside the language standard. In any case, here is the approach that I use:

(a) I'm not aware of the existence of any such list. Instead, I use the following list to determine whether a Standard Library type is likely to be designed to be inherited from:

  • If it doesn't have any virtual methods, then you shouldn't be using it as a base. This rules out std::vector and the like.
  • If it does have virtual methods, then it is a candidate for usage as a base class.
  • If there are lots of friend statements floating around, then steer clear since there is probably an encapsulation problem.
  • If it is a template, then look closer before you inherit from it since you can probably customize it with specializations instead.
  • The presence of policy-based mechanism (e.g., std::char_traits) is a pretty good clue that you shouldn't be using it as a base.

Unfortunately I don't know of a nice comprehensive or black and white list. I usually go by gut feel.

(b) I would apply LSP here. If someone calls what() on your exception, then it's observable behavior should match that of std::exception. I don't think that it is really a standards conformance issue as much as a correctness issue. The Standard doesn't require that subclasses are substitutable for base classes. It is really just a "best practice".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...