Old problem with performance

Rainer Deyke rainerd at eldwood.com
Sun Feb 8 21:03:31 PST 2009


Andrei Alexandrescu wrote:
> How long have you used C++?

My first serious C++ project was started in 1997.

> This is not a tendentious question. In the recent years, the advent of
> quality smart pointers, an increased scrutiny of use of inheritance, and
> the teaching of idioms associated with reference types has greatly
> diminished slicing accidents. But in the olden days, people were
> inheriting value types left and right because it was the emperor's new
> clothes.

Slicing is caused by naive copying of polymorphic types, which is only
tangentially related to inheriting value types.

Example 1 (C++):

struct point2d {
  int x, int y;
};

struct point3d : public point2d {
  int z;
}

'point2d' is a non-polymorphic value type.  Slicing behavior exists, is
intentional, and does not invalidate any invariants.

Example 2 (C++):

class data_source {
public:
  virtual char read_byte() = 0;
};

class input_file : public data_source {
public:
  char read_byte() = 0;
};

'input_file' is a value type that implements an interface.  No slicing
problem exists because 'data_source' is an abstract type.

Example 3 (C++):

class person {
public:
  person(person const& org) {
    assert(typeid(org) == typeid(*this));
  }
  virtual ~person() {}
};

class avatar : public person, public deity {
};

'person' and 'avatar' are value types that can be used polymorphically.
 In any context 'person&' may be either a reference to an instance of
class 'person' or a polymorphic reference to an instance of any class
that inherits from 'person'.  Unfortunately the C++ type system does not
distinguish between these two uses.  It is an error (checked at runtime)
to construct a new 'person' from a polymorphic reference, but any other
use of 'person' as a value type or a polymorphic type is valid.  No
slicing problem exists except through user error.

Example 4 (D):

class RubberChicken {
  RubberChicken dup() {
    return new RubberChicken();
  }
}

class RubberChickenWithAPulleyInTheMiddle {
  private Pulley pulley;
  // Forget to override 'dup'.
}

Here 'RubberChicken' is a reference type, but due to programmer error,
the slicing problem still exists.


-- 
Rainer Deyke - rainerd at eldwood.com



More information about the Digitalmars-d mailing list