Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

C++ static_cast runtime overhead

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(); }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...