C++ static_cast运行时开销

Pet*_*etr 19 c++ runtime overhead static-cast

请参阅下面的代码.

a)在这种情况下(简单继承,没有虚拟成员),B :: df()中的静态强制转换是否有任何开销(无论如何)?我找到了类似问题的一些相互矛盾的答案,这就是我要问的原因......

b)我正在考虑const M1 * func在A中私有化并在B中引入一个新的私有字段const M2 * func来避免演员表,但它使事情变得复杂并且更难以使用智能指针.你有没有看到避免演员的更好方法?


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(); }

Arm*_*yan 50

static_cast<T>(e) 相当于以下列方式创建一个发明的临时变量v:

T v(e); //where T is an arbitrary type  and e is an arbitrary expression.
Run Code Online (Sandbox Code Playgroud)

static_cast的运行时成本正是上述语句的成本

  • @Petr:你正在投射指针.指针的副本(无论如何可能被编译器优化)是可忽略的操作.我不会尝试优化它 (13认同)