[英]Why does a const_cast (or static_cast) not add const?
我在看這個答案 ,想使用。 但是,當使用static_cast
和const_cast
,出現分段錯誤,但是如果使用temp變量,一切都很好。 顯然是因為bar()
的非const版本將其稱為self-and-over-over。 但是我雖然static_cast
會導致const foo*
,然后選擇bar()
的const版本。 為什么會這樣?
#include <iostream>
using namespace std;
class foo
{
public:
void bar() const
{
cout << "const" << endl;
}
void bar()
{
cout << "non-const" << endl;
// static_cast<const decltype(this)>(this)->bar();
// const_cast<const decltype(this)>(this)->bar();
const auto& tmp = *this;
tmp.bar();
}
};
int main() {
foo A;
A.bar();
const foo B;
B.bar();
static_cast<const foo*>(&A)->bar();
return 0;
}
decltype(this)
是foo*
。 const decltype(this)
是foo* const
。
您無需更改指針的cv資格,而只需更改指針即可。 因此,每次都會選擇非常量重載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.