class Test
{
public:
Test() : i(0), ptr(&i) {}
int i;
int *ptr;
void change_const (int x) const { *ptr=x; }
};
int main()
{
const Test obj;
obj.ptr = &obj.i; // error
obj.change_const(99);
return 0;
}
雖然obj
ptr
是int *const
類型,構造可以使他指向const int
類型的i
。明確的嘗試做到這一點當然失敗了。爲什麼構造函數提供有關const正確性的漏洞?其他非直接明顯的漏洞如const正確性與const對象和成員指針,構造函數漏洞
int *ptr;
const int **c_ptr = &ptr; // error
const int c = 10;
*c_ptr = &c;
*ptr = 20; // because here change of c possible
也被認爲可以防止。
C++有時會給你足夠的繩子來吊死你自己。只是不要首先編寫小狗代碼,並遵守規則 –