gpt4 book ai didi

c++ - 只制作 const 对象的 const 拷贝

转载 作者:搜寻专家 更新时间:2023-10-31 00:53:14 25 4
gpt4 key购买 nike

我有一个包含引用的类,例如:

class A {
A(B &b) : b(b) {} // constructor
B &b;
}

有时b必须是只读的,有时是可写的。当我创建一个 const A a(b); 对象时,很明显我想将其中的数据保护为 const。但是 - 偶然 - 很容易制作对象的非常量拷贝,这会使其中的数据容易受到攻击。

const A a(b); // b object protected here
A a_non_const(a);
a_non_const.b.non_const_function(...); // b not protected now

我认为当对象是 const 时,我应该以某种方式阻止对象的复制:

const A a(b);
const A a2(a); // OK!
A a_non_const(a); // Compiler error

这可能吗?

最佳答案

代码中的缺陷:即使使用 const

,您的数据也未受到“保护”

const 类型限定符管理对类型成员函数的访问以及对其成员的访问。由于您的成员 B & b 是一个引用,因此 const 在这里对您没有多大作用:无论哪种方式,在初始化之后都不能更改引用。甚至没有考虑您如何访问该引用的目标:

const A a(b);
a.b.non_const_function(); // OOPS, no problem!

模板解决方案

而不是 (ab) 使用 const 类型限定符,您可以向您的类型添加一个“标志”,以区分您需要能够进行非常量访问的情况和你没有:

#include <type_traits>

struct B {
void danger() {
}
void all_fine() const {
}
};

template<bool Writeable>
struct A {
using BRef = typename std::conditional<Writeable, B &, B const &>::type;
BRef b;

A (BRef b) : b(b) {};
};

using ConstA = A<false>;
using NonConstA = A<true>;

int main() {
B b;
ConstA a(b);
//NonConstA nc_a(a);
ConstA another_a(a);
//another_a.b.danger();
another_a.b.all_fine();

NonConstA a2(b);
a2.b.danger();
}

通过一些 std::enable_if,你可以有选择地启用/禁用 A 的成员函数,具体取决于它们是否需要“可写” b还是不是。

真正的解决方案:重构你的设计

但是我想更加强调这条评论:

"Sometimes b must be read-only, sometimes it is writeable." All your problems stem from this weird duality. I suggest picking one set of semantics for your class, not two

From Lightness Races in Orbit

您可能应该考虑拆分您的类,这样您就有一个 CommonA,其功能由 WriteableANonWriteableA (名字很糟糕,但我希望你明白我的意思)。

关于c++ - 只制作 const 对象的 const 拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49406521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com