c++ 中受保护访问中的数据损坏

发布于 2024-07-12 04:03:21 字数 53 浏览 6 评论 0原文

“受保护”的变量容易被派生类恶意更改? 我应该在基类变量中使用“私有”而不是“受保护”吗?

Variables "protected" are prone to be malicious changed by derived class?
Should I use "private" in base class variables instead of "protected"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

世俗缘 2024-07-19 04:03:21

如果您担心“恶意”修改,那么即使将数据标记为 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.

‖放下 2024-07-19 04:03:21

在 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.

绝不服输 2024-07-19 04:03:21

好吧,受保护的成员确实会被继承。 如果您不希望发生这种情况,请将它们设置为私有。

Well, protected members do get inherited. If you don't want that to happen, make them private.

七秒鱼° 2024-07-19 04:03:21

一般来说,如果您正在考虑声明私有变量,您应该退一步问自己为什么要在头文件中发布声明?

而不是在 foo.h 中向全世界公开您的成员变量:

class foo {
private:
    int    please_dont_modify_me;
    double pretend_you_dont_see_this_declaration;
    char   dont_look_at_this [128];
public:
    ....
};

只需使用不完整的私有类型,即定义:

class foo {
    struct foo_privates & mine;   // incomplete type
public:
    ...
};

然后在 foo.cpp ONLY 中:

struct foo_privates {
     int    i;
     double d;
     char   str[128];
}; 

当然, 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:

class foo {
private:
    int    please_dont_modify_me;
    double pretend_you_dont_see_this_declaration;
    char   dont_look_at_this [128];
public:
    ....
};

just use an incomplete private type, that is not defined:

class foo {
    struct foo_privates & mine;   // incomplete type
public:
    ...
};

then in foo.cpp ONLY:

struct foo_privates {
     int    i;
     double d;
     char   str[128];
}; 

Of course, the constructor for foo has to allocate the separate object and the destructor has to destroy it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文