如果在保持相同类型的情况下添加constness,static_cast运行时开销是什么? [英] What is the static_cast runtime overhead if adding constness while keeping the same type?
问题描述
我觉得很恼火,如果我有一个指向这个对象的指针,我可以调用一个对象的非const函数。我不能让指针是一个const指针,因为还有非const函数我需要调用。因此,我唯一的选择似乎做static_casts,以确保constness也可以工作在指针。这是一个最小的例子:
class MyClassImpl
{
MyClassImpl(void):m_i {}
int increment(void){
++ m_i;
return m_i;
}
private:
int m_i;
};
class MyClass
{
MyClass(void):m_pImpl(new MyClassImpl()){}
〜MyClass b删除m_pImpl;
}
int doNothing(void)const {
m_pImpl-> increment(); // works while MyClassImpl :: increment()is non-const
// static_cast< const MyClassImpl *>(m_pImpl) - > increment(); //这不会编译因为非常量
}
private:
MyClass(const MyClass& rhs);
MyClassImpl * m_pImpl;
};但是,我不知道static_cast在运行时是否有任何代价。
$ b <在编译时static_cast是完全评估,或者有一些开销,假设常常调用doNothing()。
编辑:
我的问题不同于 C ++ static_cast运行时开销,因为在我的case,static_cast只添加const。
运行时开销本质上是一个指针副本,可能是
在你的情况下,我会考虑改变 int m_i;
到 mutable std :: atomic< int> m_i;
并在基类中使增量
常量。它看起来像一个引用计数器,我的方式允许你(i)保留 const
-correctness和(ii)线程安全。我还会考虑将 int
更改为 unsigned
,以避免未定义的行为if m_i
太大了。 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.
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.
这篇关于如果在保持相同类型的情况下添加constness,static_cast运行时开销是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!