通过构造从结构到其指针和参考成员
Pass through constness from a struct to its pointer and reference members
我有一个带有指针的结构。我想做到这一点,所以如果结构实例是const,则无法修改其指针的内容。
struct Foo {};
struct Bar {
Foo /*const goes here if `const Bar`*/ *foo;
};
void f(Bar& bar) {
*bar.foo = Foo(); // OK
}
void g(const Bar& bar) {
*bar.foo = Foo(); // OK - but should be error
}
是否有一种方法可以通过构造从结构到指针和参考成员?
封装在救援中!
只是通过接口访问Marshall:
struct Bar {
Foo * getFoo() { return foo; }
Foo const * getFoo() const { return foo; }
private:
Foo *foo;
};
void f(Bar& bar) {
*bar.getfoo() = Foo(); // OK
}
void g(const Bar& bar) {
*bar.getfoo() = Foo(); // Error!
}
您正在与语言作斗争,不要那样做。就像在上游游泳一样 - 您只会疲倦,而不喜欢结果。
可以通过使用私人数据和成员函数来解决您的问题:
struct Foo {};
struct Bar {
void reset() {
*foo = Foo();
}
private:
Foo *foo;
};
void f(Bar& bar) {
bar.reset(); // OK
}
void g(const Bar& bar) {
bar.reset(); // fails, as reset is not declared const
}
使const推动智能指针:
template<typename T>
struct const_ptr : std::unique_ptr<T> {
using std::unique_ptr<T>::unique_ptr;
const T& operator*() const {
return std::unique_ptr<T>::operator*();
}
const T* operator->() const {
return std::unique_ptr<T>::operator->();
}
T& operator*() {
return std::unique_ptr<T>::operator*();
}
T* operator->() {
return std::unique_ptr<T>::operator->();
}
};
然后,试图通过const const_ptr
突变对象引用将导致错误:
const_ptr<int> iptr = std::make_unique<int>(6);
*iptr = 7; // okay
const auto ciptr = std::move(iptr);
*ciptr = 2; // error
但是,请注意,由于我们公开扩展std::unique_ptr
,因此他的功能仍然可用。您可能需要使用私有继承并使用所有其他功能,除了我们的自定义功能:
template<typename T>
struct const_ptr : private std::unique_ptr<T> {
using std::unique_ptr<T>::unique_ptr;
// Implement our operators like above
using std::unique_ptr<T>::release;
using std::unique_ptr<T>::reset;
// .. all other public functions
};
相关文章:
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 类的方法和对象。参考?智能指针?简单的初始化?
- 我正在学习C++,我不能使用指针访问参考吗?(举个例子)
- 使用指针向量到参考向量是非法的吗?
- 函数参数绑定通过参考与传递指针传递数组的规则
- 参考参考static_cast的成本和指向指针static_cast的指针
- 函数采用原始指针试图通过错误msg中概述的参考来接受指针
- 为什么即使传递给函数作为参考,指针也未被分配
- 为什么通用参考概念不适用于函数指针的地图插入
- 是指代指针正交的参考文献
- 超载函数既不按值,也不是通过参考来对象,而是将撤销的指针换成对象
- 从参考中获取的指针可以在定义明确的C 中取无效
- 指针与参考示例,在什么情况下更好
- 为什么要拿参考的地址给我一个第二等级的指针
- 如何提升::序列化指针和参考
- 在范围外丢失指针参考
- 将std ::向量作为指针参考
- 从指针参考C 创建一个新对象
- 从基本指针/参考调用正确的免费功能
- 在操作员过载的情况下处理悬空指针/参考