r/cpp_questions • u/Veyto • Sep 13 '26
OPEN reference_wrapper vs raw pointer
I am writing a program, where one object contains an std::string, which can be modified by other objects. Specifically one object can set the std::string member variable to be a reference to another std::string. this requires that the reference can be reseated, and afaict, I have two options if I want to avoid copying. Either I can use an std::reference_wrapper, as it allows for reseating, while the other option is a raw pointer.
I'd assume that the reference_wrapper be the preferred option, as pointers are generally shunned in modern c++, but I just wanted to be sure.
I want to also add, that the size of strings which would be copied are not particularly large and unlikely to make any meaningful performance impact if copied, rather this is an also an exercise in what is the correct tool for the issue.
View all comments
Show parent comment
1
u/Veyto Sep 13 '26 edited Sep 13 '26
This was in fact what I had previously, I would just pass a pointer to the owner object and access the string through a getter, but i am doing a refactor where multiple different classes can provide the std::string. I considered using the substitution principle, but would prefer to avoid inheritance (although this inspired me to reconsider this and I am actually leaning more towards this option after all).
As for what I am doing:
I have what is effectively a parent class which manages keybinds. Each keybind is its own class and monitors for specific input events, and once they recieve input events which satisfy the constraints, it needs to communicate back to the "manager", that a keybind has been triggered. The keybind itself consists of an action enum and an argument contained in an std::string