为何使用算术和访问运算符进行上传

时间:2011-10-18 09:46:58

标签: c++ performance

在代码中用C ++向上转换的原因是什么?这些代码将用于对大量数据(我正在使用的库)进行数值计算?

考虑以下层次结构:

template<class T>
class unallocatedArray
{
    public: 
        unallocatedArray(int size, T t)
            : size_(size), t_(0) 
        {

        }

        // Copy constructor. This is the only way to 
        // actually allocate data: if the array is 
        // passed as an argument to the copy constr.
        // together with the size. 

        // Checks. Access operators. Iterators, etc.  
        // Wrappers for stl sorts...

    private:
        int size_;
        T* t_;
};


template<class T>
class myArray 
: public unallocatedArray<T>
{
    public:
        // This type actually allocates the memory.
        myArray (int size)
            : unallocatedArray<T>(size)
        {
            // Check if size < 0..  

            // Allocate.
            this->t_ = new T[size];
        }

        myArray (int size, T t)
        {
            this->t_ = new T[size];

            for (int i = 0; i < this->size_; i ++ )
            {
                this->t_[i] = t;
            }
        }

        // Some additional stuff such as bound checking and error handling. 
        // Append another array (resizing and memory copies), equality 
        // operators, stream operators, etc...

};

template<class T>
class myField
: public myArray<T>
{
    public: 
        // Constructors call the parent ones. No special attributes added. 

        // Maping operations, arithmetical operators, access operator.
};

//

template<class T>
class geomField
: public myField<T>
{
    // myField but mapped on some kind of geometry, like surface meshes, 
    // volume meshes, etc.  
};

这只是一个非常简化的模型,只是声明访问运算符是一直定义的,并且算术运算符放在myField类中。现在,将geomField向上转换为myField的原因是什么,如果需要执行以下1e07次:

访问该元素 执行算术表达

以下列方式:

GeomField<myType> geomFieldObject;

myField<myType>&  downCast = geomFieldObject;

// Do the arithmetical operations on the downCast reference. 

这两个领域?是不是也在向上引入某种惩罚?算术运算符是否不公开给geomField:这不是公共继承的全部意义吗?

我没有设计这个,它来自我正在开发的os库。:)

谢谢!

1 个答案:

答案 0 :(得分:1)

我只能猜测,但是为了实现几何映射,可能会在geomField中覆盖一些算术运算。

如果您在geomField中有数据但想要执行未映射的操作,则可能是向上转发的原因。

另一方面,如果在geomField中没有覆盖在铸造参考上执行的任何操作,那么你就没有必要进行铸造。

通常,向上转换不会引入任何性能缺陷,因为通常(或者甚至在每种情况下,我现在都不确定......)它完全在编译时完成:考虑以下类:

class A {
public:
  void f();
};

class B : public A {
public:
  void f(); // Overwrites A::f
};

当您的代码看起来像

B obj;
obj.f();

它被编译器翻译成类似

的东西
B::f(&obj);

static_cast<A>(obj).f();

结果

A::f(&obj);

即。没有通过强制转换引入的运行时开销。

相关问题