如何为句柄类提供运算符 -> 的常量版本

How to provide const version of operator -> for a handle class

本文关键字:gt 版本 常量 运算符 句柄      更新时间:2023-10-16

我正在尝试重载我的运算符>,以便句柄类返回常量和非常量指针,指向基类。

查看我发布的代码,在试用函数中,如果我添加 const 关键字,错误消息将是

||=== Build: Debug in Const trial (compiler: GNU GCC Compiler) ===|
C:Const trialmain.cpp
||In function 'bool trial(Cards_pointer)':|
C:Const trialmain.cpp|50|error: passing 'const Cards_pointer' as 'this' argument of 'Cards*& Cards_pointer::operator->()' discards qualifiers [-fpermissive]|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

我的问题是是否可以这样做,如果是,我可以知道正确的实现是什么吗?

#include <iostream>
#include<vector>
#include<stdexcept>
#include<algorithm>
using namespace std;
class Cards
{
private:
int x;
public:
Cards():x(3) {}
int rx()const
{
return x;
}
};
class Cards_pointer
{
private:
Cards* cp;
size_t* refptr;
public:
//default constructor
Cards_pointer():cp(0),refptr(new size_t(1)) {}
Cards_pointer(Cards*t):cp(t),refptr(new size_t(1)) {}
//copy constructor
Cards_pointer (const Cards_pointer&s):cp(s.cp),refptr(s.refptr)
{
refptr=s.refptr;
cp=s.cp;
//++*refptr;
*refptr=*refptr+1;
}
Cards*&operator->()
{
if(cp)
return cp;
else throw std::runtime_error("uninitialized Cards");
}
};
bool trial(const Cards_pointer x)
{
if(x->rx()==3)
return true;
return false;
}
int main()
{
Cards_pointer x=new Cards();
bool cond=trial(x);
}

只需返回一个指向 const 的指针,并提供一个 const 限定的重载

class Something {
public:
void bar() {}
void foo() const {}
};
class Wrapper {
public:
Something* operator->() {
return &this->something;
}
const Something* operator->() const {
return &this->something;
}
private:
Something something;
};
int main() {
const auto c_wrapper = Wrapper{};
c_wrapper->foo();
// The below is an error
// c_wrapper->bar();
auto m_wrapper = Wrapper{};
m_wrapper->bar();
}

如果您担心 const 和非 const 重载中的代码重复,请参阅 Const 函数调用 non const 反之亦然(以避免重复)?

如果你重载你的operator->,行为将不会模仿内置指针的行为(并且根本没有多大意义)。

内置指针有两种形式:指针和指向常量的指针。(我们在这里忽略易失性)。这些口味是不同的类型。指针本身是常量与它们所指向内容的恒定性无关。

为了模仿这种行为,您需要两种Cards_pointer,一种是返回普通指针的operator->,另一种是返回指向常量的指针的operator->

class Cards_pointer_base { ... };
class Cards_pointer: private Cards_pointer_base {         
public:
// usual constructors/assignment operators
using ...; // necessary members from the base
Cards* operator->() { ... }
};
class Cards_const_pointer: private Cards_pointer_base {         
public:
// usual constructors/assignment operators
using ...; // necessary members from the base
const Cards* operator->() { ... }
// conversions from pointer to non-const
Cards_const_pointer(const Cards_pointer& from) { ... }
Cards_const_pointer& operator=(const Cards_pointer& from) { ... }
};

标准的智能指针是类模板,因此可以只编写shared_ptr<Cards>shared_ptr<const Cards>