gpt4 book ai didi

c++ - 具有引用语义的 Const 对象

转载 作者:行者123 更新时间:2023-11-28 03:15:20 28 4
gpt4 key购买 nike

我有一个用户用来与系统交互的类。此类使用 Pimpl 来隐藏其内部结构,因此它唯一的实际成员是对完成所有工作的真实隐藏对象的引用。

因为类具有引用语义,所以它通常像指针一样按值传递。这会导致 const 正确性出现问题。您可以通过简单地将 const 值复制到非 const 值来轻松打破类的 const 性质。除了完全防止复制之外,没有其他方法可以避免这种情况。

我希望能够返回这些的 const 值,这保留了对象的 const 性质。 无需创建新类或其他东西。

基本上我想阻止它工作:

struct Ref
{
int &t;
Ref(int &_t) : t(_t) {}
};

Ref MakeRef(int &t) { return Ref(t); }

int main()
{
int foo = 5;
const Ref r(foo);
const Ref c(r); //This should be allowed.
Ref other = MakeRef(foo); //This should also be allowed.
Ref bar(r); //This should fail to compile somehow.

return 0;
}

毕竟我直接做是不行的:

int &MakeRef(int &t) {return t;}

int main()
{
int foo = 5;
const int &r(foo);
const int &c(r); //This compiles.
int &other = MakeRef(foo); //This compiles.
int &bar(r); //This fails to compile.

return 0;
}

最佳答案

这与合并 const T*T* const 产生的问题完全相同:引用和被指对象的可变性是不同的。所有四种可能的组合在 C++ 中都有有效的用例。我会为“对 T 的引用”和“对 const T 的引用”创建不同的类型:

#include <type_traits>

template <typename T>
struct Ref
{
T &t;
Ref(T &_t) : t(_t) {}
Ref(const Ref<typename std::remove_cv<T>::type>& other) : t(other.t) {}
};

template <typename T>
Ref<T> MakeRef(T& t) { return {t}; }

template <typename T>
Ref<const T> MakeConstRef(const T& t) { return {t}; }

int main()
{
int foo = 5;
auto r = MakeConstRef(foo);
auto c = r; // This is allowed.
auto other = MakeRef(foo); // This is also allowed.
Ref<const int> baz = other; // This works, too.
Ref<int> bar = c; // This fails to compile, as desired.
}

Live example at ideone .

关于c++ - 具有引用语义的 Const 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17097708/

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