What is the static_cast runtime overhead if adding constness while keeping the same type?

本秂侑毒 提交于 2019-12-20 04:27:11

问题


I find it irritating that I can call non-const functions of an object if I have a pointer to this object. I cannot let the pointer be a const pointer because there are also non-const functions I need to call. Therefore, my only option seems to do static_casts to ensure that constness also works across pointers. Here is a minimal example:

class MyClassImpl
{
  MyClassImpl(void) : m_i(0) {}

  int increment(void) {
    ++m_i;
    return m_i;
  }

  private:
    int m_i;
};

class MyClass
{
  MyClass(void) : m_pImpl(new MyClassImpl()){}

  ~MyClass(void) {
    delete m_pImpl;
  }

  int doNothing(void) const {
    m_pImpl->increment(); // works although MyClassImpl::increment() is non-const
    // static_cast<const MyClassImpl *>(m_pImpl)->increment(); // this will not compile because of non-constness
  }


  private:
  MyClass(const MyClass & rhs);
  MyClassImpl * m_pImpl;
};

However, I wonder if the static_cast has any cost at runtime. Are static_casts completely evaluated at compile time or is there some overhead, assuming that doNothing() is called often.

Edit: My question is different from C++ static_cast runtime overhead because in my case, the static_cast only adds const. Other users finding this question might be interested in the mentioned question.


回答1:


The runtime overhead is essentially a pointer copy, which may be optimised out altogether.

But in your case, I'd consider changing int m_i; to mutable std::atomic<int> m_i; and make increment constant in the base class too. It looks like a reference counter and my way allows you to (i) retain const-correctness and (ii) be thread safe. I'd also consider changing int to unsigned to avoid undefined behaviour if m_i gets too big.



来源:https://stackoverflow.com/questions/32068014/what-is-the-static-cast-runtime-overhead-if-adding-constness-while-keeping-the-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!