关于C++:通常应该永远不应该公共子类vector <>但是如果只是方便的方法呢?

normally should never public subclass vector<> but what if just convenient methods?

本问题已经有最佳答案,请猛点这里访问。

这不是"You cannot inherit from std::vector"的副本,后者要求添加"algorithms"而不是方法。

很明显,如果有额外的成员,就会有一个切片问题,但是没有。

如果有任何方法被忽略,则可能会有其他一些意外的行为,但事实并非如此。

规范指出,通过带有非虚拟析构函数的基类指针删除对象是未定义的,但假定我有自己的控制权不执行此操作,并且如果执行了此操作,则我的实现将自动成功(正如我假定的那样;任何已知的异常?)

似乎没有问题的参考或分配到标准向量,因为唯一失去的是额外的方法。

我发现自己不断重复的新方法的即兴创意:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
T& allow( size_t x ) { // grows the vector when necessary.
    if ( size() <= x )
        resize( x+1 );
}

T& ok( size_t x ) { // get lvalue, growing the vector when necessary.
    allow( x );
    return operator[]( x );
}

int size() { // return type is int, which is much more convenient; limits you to
             // MAXINT elements but enough for all code I've written in 26 years.
    return (int) vector<T>::size();
}

T& back( int i = 0 ) { // gives you back element, or indexed, gives Nth back.
    return operator[]( size() - i - 1 );
}


Exel.DeleTe/3:

In a single-object delete expression, if the static type of the object to be deleted is different from its dynamic type and the selected deallocation function (see below) is not a destroying operator delete, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined. In an array delete expression, if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.