gpt4 book ai didi

C++:防止在 const 函数中更改指针的值

转载 作者:搜寻专家 更新时间:2023-10-31 02:08:07 24 4
gpt4 key购买 nike

采用这个虚拟结构:

struct foo
{
int* pI;
void bar() const
{
int* ptrToI = pI; // I want this to require 'const int*'
*ptrToI = 5; // I want this to fail
}
}__test__;

如何设计此结构以防止我更改 pI 指向的值?

最佳答案

您可以使用自定义智能指针来隐藏底层指针:

template <typename T>
struct ptr_t
{
private:
T *ptr;
public:
//Constructors and assignment operators
ptr_t(): ptr(nullptr) {}
ptr_t(T* p): ptr(p) {}
ptr_t(const ptr_t &other): ptr(other.ptr) {}
ptr_t& operator=(T* p) {this->ptr=p;return *this;}
ptr_t& operator=(const ptr_t &other) {this->ptr=other.ptr; return *this;}

//Note that the smart pointers included in the standard returns non-const pointers
//That is why you need to define a custom smart pointer, which forces the const pointer return in the const version of the operators.
const T* operator->() const {return ptr;}
T* operator->() {return ptr;}
const T& operator&() const {return *ptr;}
T& operator&() {return *ptr;}

operator const T*() const {return ptr;}
operator T*() {return ptr;}
};

struct foo2
{
ptr_t<int> pI;
void nonconst_bar()
{
int* ptrToI = pI; // Now success, since not const
*ptrToI = 5;
}

void failing_bar() const
{
//int* ptrToI = pI; // This fails
//*pI = 5; // This also fails
}

void success_bar() const
{
const int* ptrToI = pI;
//*ptrToI = 5; // This is not possible anymore
}
};

关于C++:防止在 const 函数中更改指针的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47921835/

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