[英]Is const_cast on “this” pointer an undefined behavior?
我有以下c ++代碼。 我可以在Linux機器上使用g ++ 4.9.2進行編譯。 然后,當我運行它時,它會顯示10。似乎在默認構造函數中創建了一個新對象並將其分配給使用const_cast創建的指針。 沒有內存泄漏(我使用valgrind檢查了)。 這是某種未定義的行為還是合法的?
#include <iostream>
using namespace std;
class A
{
public:
A() : x(0)
{
A *tmp = const_cast<A*>(this);
*tmp = A(10);
}
A(int x)
{
this->x = x;
}
int getX() const
{
return x;
}
private:
int x;
};
int main()
{
A a;
cout << a.getX() << endl;
return 0;
}
const_cast
與您遇到的行為無關。 您的代碼可以簡化為以下內容:
A() : x(0)
{
*this = A(10);
}
因此,如果要使用默認構造函數創建對象,則會發生以下情況:
this
被保留。 0
分配給this
的成員x
。 A
使用構造創建A(int)
這個新的對象成員x
值為10
。 *this
。 因此,部件的值x
的this
becames 10
。 this
被返回。 這是完全合法和預期的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.