C++ static_cast 运行时开销
请参阅下面的代码。
a) 在这种情况下(简单继承,无虚拟成员),B::df() 中的静态转换是否有任何开销(无论如何)?我发现类似问题的一些相互矛盾的答案,这就是我问的原因...
b) 我正在考虑将 A 中的 const M1 * func 设为私有,并引入一个新的私有字段 const M2 * func 到 B 以避免强制转换,但这使事情变得复杂并且使智能指针的使用变得更加困难。您是否有更好的方法来避免演员阵容?
class M1 {
public:
double f() const;
};
M2 类:公共 M1 {
民众:
双 df() 常量;
};
A类{
受保护:
常量 M1 * 函数;
民众:
A(const M1 * p);
〜A();
双 f() 常量;
};
B 类:公共 A {
民众:
B(常量 M2 * p);
双 df() 常量;
};
double M1::f() const { return 1973.0; }
double M2::df() const { return 0.0; }
A::~A() { 删除函数; }
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(func)->df(); }
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 field const 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(e)
相当于通过以下方式创建发明的临时变量 v:static_cast 的运行时成本正是上述语句的成本
static_cast<T>(e)
is equivalent to creating an invented temporary variable v in the following way:The runtime cost of a static_cast is exactly the cost of the above statement