2014-11-21 109 views
0

我的朋友创建了这个代码,它将访问类的内存并更改私有变量的值。C++访问内存类并更改私有变量

#include <iostream> 

using namespace std; 

class has_private_variable 
{ 
private: 
    const int member1; 
public: 
    has_private_variable() 
    : member1(5) //initializer list. In case you haven't seen that before 
    { 
    } 
    int getMember1() 
    { 
     return member1; 
    } 
}; 

int main() 
{ 
    has_private_variable hpv; 
    int tmp = hpv.getMember1(); 
    cout << hpv.getMember1() << endl; 
    char* ptr = (char*)&hpv; //Yeah this will generate all types of warnings hopefully 
    //find the actual address of the member 
    while (*(int*)ptr != tmp) 
     ptr++; 
    int* ptr_int = (int*)ptr; 
    *ptr_int = 3; 
    cout << hpv.getMember1() << endl; 
    //There's a joke in here about hpv.vaccinate(), but I can't be bothered to find it 
    return 0; 
} 

这样做的能力看起来好像破坏了拥有私有变量的整个观点。 有没有一些方法来阻止程序员能够像这样访问私有变量?

编辑:

从我得到,我的朋友被调用的C未定义行为++的意见。但有没有办法让程序员可能无法做到这一点?

+5

引用@Jerry Coffin:“C++试图预防事故,而不是故意颠覆(又名”保护墨菲,而不是马基雅维利“)。” – vsoftco 2014-11-21 18:55:37

+0

或者:C++不会阻止你做任何你想做的事情(必须完成的事情)。它只会警告你,如果它看起来很危险,你没有声称你是对的。 – Deduplicator 2014-11-21 18:59:19

+0

你的朋友已经调用了未定义的行为,它纯粹的机会有访问私有变量的效果。 [阅读关于未定义的行为](http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior)。 – 2014-11-21 19:54:36

回答

0

,便有可能使用专用的模板类,模板类,使私有成员和一个隐藏的内存位置静态分配的:

template<typename type> 
class true_private 
{ 
public: 
    ~true_private() 
    { 
     type local; 
     get_set(-1, local); 
    } 

    true_private(type value) 
    { 
     type local = value; 
     get_set(0, local); 
    } 

    void get_set(int op, type& value) 
    { 
     static type* var = 0; 

     if(var == 0) 
      var = new type(); 

     if(op == 0) // set 
      *var = value; 

     else if(op == 1) // get 
      value = *var; 
     else // delete 
      delete var; 
    } 

    type Get() 
    { 
     type local; 
     get_set(1, local); 
     return local; 
    } 

    void Set(type value) 
    { 
     type local = value; 
     get_set(0, local); 
    } 
}; 

class has_private_variable 
{ 
private: 
    true_private<int> member1; 
public: 
    has_private_variable() 
    :member1(5) //initializer list. In case you haven't seen that before 
    { 
    } 
    int getMember1() 
    { 
     return member1.Get(); 
    } 
}; 

这仅仅是一个锻炼,以显示模板类的力量:)