1

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.

Community
  • 1
  • 1
Fabian
  • 4,001
  • 4
  • 28
  • 59

1 Answers1

2

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    Why would the pointer be copied ? In that case, only `const`-qualification changes, so it's most probably a no-op. – Quentin Aug 18 '15 at 09:13
  • 1
    Indeed, the compiler might optimise out a temporary. But it's no **worse** than a pointer copy. – Bathsheba Aug 18 '15 at 09:14