我正在尝试创建一个类,它是具有特定状态的消息传递的处理程序。 准备好消息后,我希望创建一个新的
state_t
结构体来引用新的“y”数据。我希望能够通过相同的 state
变量访问新对象。
一个带有指针的最小示例如下所示:
class Handler {
int x; // something config for the handler
struct state_t {
int *y;
state_t(int *y) : y(y) {}
};
std::optional<state_t> state;
Handler(int x) : x(x), state(std::nullopt) {}
void prepare_message(int *y) {
state = state_t(y);
}
void handle_state() {
// do something with the y e.g. send it over a socket
}
};
我想知道是否有一个好方法可以通过引用而不是指向
y
的指针来完成这项工作。直接替换它不会编译,因为复制分配被隐式删除。可以通过优雅的方式克服这个问题吗?
正如@RemyLebeau 评论,你可以使用
std::reference_wrapper
。std::reference_wrapper 是一个类模板,它将引用包装在可复制、可分配的对象中。
这在下面进行了演示。
请注意,我添加了一个公共
test()
方法来表明 state_t
现在是可复制的。我还将 Handler
的构造函数设为公共,以便从 main
创建它。
#include <optional>
#include <iostream>
class Handler {
[[maybe_unused]] int x; // something config for the handler
struct state_t {
//------vvvvvvvvvvvvvvvvvvvvvv--------
std::reference_wrapper<int> y;
state_t(int & y) : y(y) {}
};
std::optional<state_t> state;
void prepare_message(int & y) {
state = state_t(y);
}
void handle_state() {
}
public:
Handler(int x) : x(x), state(std::nullopt) {}
// Demonstration that `state_t` is now copyable:
void test() {
int x1 = 1;
int x2 = 2;
state_t s1{ x1 };
state_t s2{ x2 };
std::cout << s1.y << "\n";
s1 = s2;
std::cout << s1.y << "\n";
}
};
int main() {
Handler h{ 5 };
h.test();
}
输出:
1
2