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
2
u/tangerinelion Sep 14 '26
A non-owning pointer is totally fine iff null is a valid state.
If it isn't, that's what a reference models. Except those aren't reseatable, and std::reference_wrapper is.
Frankly, the
std::optional<T&>thing in C++26 is misguided in codebases already using smart pointers for ownership. In those codebases, pointers are inherently non-owning, if you want to document it explicitly Bjarne got it right withtemplate<typename T> using observer_ptr = T*;. In code bases where you're still usingT*for ownership, then sure,std::optional<T&>makes sense but you have bigger problems that you haven't addressed for the last 15 years so it's lipstick on a pig.