c++ 中受保护访问中的数据损坏
“受保护”的变量容易被派生类恶意更改? 我应该在基类变量中使用“私有”而不是“受保护”吗?
Variables "protected" are prone to be malicious changed by derived class?
Should I use "private" in base class variables instead of "protected"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您担心“恶意”修改,那么即使将数据标记为
private:
也无济于事。C++ 访问说明符仅对本质上遵守规则的代码有用。
将成员标记为
private
将防止班级的普通用户干扰他们。 然而,即使是有错误的非恶意代码也可能会破坏这些成员。 溢出、有问题的指针算术或强制类型转换的不当使用都会让 C++ 程序员导致这些问题。If you're worried about 'malicious' modifications, then even marking data as
private:
will not help.The C++ access specifiers are only useful for code that's essentially playing by the rules.
Marking a member as
private
will prevent normal users of your class from messing with them. However, even non-malicious code that has bugs can corrupt those members. Overruns, buggy pointer arithmetic or improper use of casts lets a C++ programmer cause these problems.在 C++ 中无法阻止“恶意”访问,因为您始终可以以某种方式绕过编译器限制。 如果您担心“意外”更改,请继续将其设为私有。
"Malicious" access can't be prevented in C++, because you can always get around the compiler restrictions somehow. If you're worried about "accidental" changes, go ahead and make it private.
好吧,受保护的成员确实会被继承。 如果您不希望发生这种情况,请将它们设置为私有。
Well, protected members do get inherited. If you don't want that to happen, make them private.
看一下:http://www.parashift .com/c++-faq-lite/private-inheritance.html#faq-24.5
您可能想要私有。
Take a look at: http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.5
You probably want private.
一般来说,如果您正在考虑声明私有变量,您应该退一步问自己为什么要在头文件中发布声明?
而不是在 foo.h 中向全世界公开您的成员变量:
只需使用不完整的私有类型,即未定义:
然后在 foo.cpp ONLY 中:
当然, foo 的构造函数必须分配单独的对象,而析构函数必须销毁它。
In general, if you're contemplating declaring a private variable, you should step back and ask yourself why are you even publishing the declaration in the header file?
instead of exposing your member variables for all the world to see in foo.h:
just use an incomplete private type, that is not defined:
then in foo.cpp ONLY:
Of course, the constructor for foo has to allocate the separate object and the destructor has to destroy it.