C ++ static_cast运行时开销 [英] C++ static_cast runtime overhead
问题描述
请参阅下面的代码。
a)在这种情况下(简单继承,没有虚拟成员),B :: df任何开销(任何)?我发现了类似问题的一些冲突的答案,这就是为什么我问...
b)我正在考虑使 const M1 * func
private在A中,并引入一个新的私有字段 const M2 * func
到B,以避免强制转换,但它使事情复杂化,智能指针更难。
class M1 {
public :
double f()const;
};
class M2:public M1 {
public:
double df()const;
};
class A {
protected:
const M1 * func;
public:
A(const M1 * p);
〜A();
double f()const;
};
class B:public A {
public:
B(const M2 * p);
double df()const;
};
M1 :: f()const {return 1973.0; }
double M2 :: df()const {return 0.0; }
A ::〜A(){delete func; }
A :: A(const M1 * p):func(p){}
double A :: f()const {return func-> f }
B :: B(const M2 * p):A(p){}
double B :: df()const {return static_cast< const M2 *>(func)→df(); }
解决方案
static_cast< T>(e)
等价于以下列方式创建发明的临时变量v:T v(e); //其中T是任意类型,e是任意表达式。
static_cast的运行时成本正是上述语句的成本
See the code below.
a) Does, in this case (simple inheritance, no virtual members), the static cast in B::df() have any overhead (whatsoever)? I found some conflicting answers to similar questions, that's why I am asking...
b) I was thinking about making
const M1 * func
private in A and introducing a new private fieldconst M2 * func
into B to avoid the cast, but it kind of complicates things up and makes use of smart pointers more difficult. Do you see a better way to avoid the cast?class M1 { public: double f() const; };
class M2 : public M1 { public: double df() const; };
class A { protected: const M1 * func; public: A(const M1 * p); ~A(); double f() const; };
class B : public A { public: B(const M2 * p); double df() const; };
double M1::f() const { return 1973.0; } double M2::df() const { return 0.0; }
A::~A() { delete func; } A::A(const M1 * p) : func(p) {} double A::f() const { return func->f(); }
B::B(const M2 * p) : A(p) {} double B::df() const { return static_cast<const M2*>(func)->df(); }
解决方案
static_cast<T>(e)
is equivalent to creating an invented temporary variable v in the following way:T v(e); //where T is an arbitrary type and e is an arbitrary expression.
The runtime cost of a static_cast is exactly the cost of the above statement
这篇关于C ++ static_cast运行时开销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!