Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 902
Petr Avatar asked Jun 22 '11 20:06

Petr


People also ask

Does static_cast take time?

static_cast MAY take time at run-time. For example, if you convert int to float then work is required. Usually casting pointers does not require any run-time cost.

Is static_cast faster than Dynamic_cast?

While typeid + static_cast is faster than dynamic_cast , not having to switch on the runtime type of the object is faster than any of them.

Can I use static_cast in C?

Static casts are only available in C++.

When should I use static_cast?

This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc.


1 Answers

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

like image 145
Armen Tsirunyan Avatar answered Sep 21 '22 14:09

Armen Tsirunyan