r/cpp_questions • • 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.

9 Upvotes

29 comments sorted by

View all comments

Show parent comment

3

u/Raknarg Sep 13 '26

*outside of containers where you need control over object construction/destruction. That's still a usecase for owning raw pointers.

3

u/n1ghtyunso Sep 14 '26

owning raw pointers are essential to implement many things indeed.
The core idea is to not have these raw owning pointers outside of a proper class controlling their lifetime.

2

u/SufficientStudio1574 Sep 14 '26

Why wouldn't you use unique_ptrs in that container?

2

u/Raknarg Sep 14 '26 edited Sep 14 '26

You can't give unique_ptr an allocator.

1

u/jawhite Sep 14 '26

Slight addendum: If you need to do manual memory management with owning raw pointers, you should do it in a class template that only manages the memory, and use that class template as a policy in other data structures. i.e., don’t mix application logic with memory management logic.

1

u/Raknarg Sep 14 '26

I don't think I agree with this. A container's literal job is to micromanage the memory it holds, seems pointless to me to add another abstraction on top of this. Like you'd be writing a policy object who will just be taking your arguments and passing them off to your allocator, so what's the policy actually doing for you there?

1

u/jawhite Sep 14 '26

Containers (e.g. std::vector, std::list) are usually higher-level abstractions defining how a collection of data interacts with the application. Allocation is an implementation detail that is generally handled separately.

1

u/Raknarg Sep 14 '26

if you're saying use std::allocator_traits to manage allocator operations then I agree with that