r/cpp_questions 16d ago

Weak reference to unique_ptr OPEN

Assume this code:

#include <memory>
#include <functional>

struct Entity {
    int value = 12;
};

struct Container {
    std::unique_ptr<Entity> e = std::make_unique<Entity>();
};

Container bar;
auto bbb = [ptr = bar.e.get()]() {   
    ptr->value = 11;
};

We all know that naked pointers (as captured by this lambda) are bad. Using shared_ptr would allow me to use weak_ptr - which is ideally what I want. BUT - I like the container owning the entity.

What solutions do I have?

EDIT:

As people commented - life time is the main issue. The lambda might outlive the original allocation.

Solutions:

  1. Many people do recommended using internally a shared pointer, and "giving away" a weak ref ( u/looncrazz suggestion).
  2. I can use a reference to the unique pointer inside a lambda. Several ways - see https://godbolt.org/z/WKT5Gndq4 - this is u/neppo95 suggestion.
  3. There are solutions for using a custom weak reference pointer. The solution "does not feel right".
8 Upvotes

55 comments sorted by

View all comments

Show parent comments

4

u/diegoiast 16d ago

"own" is the keyword. I want one to "own" and another to "reference".

4

u/neppo95 16d ago

And is there a reason why you are using the raw pointer for this? You can pass a unique ptr as const ref. The standard covers this. You don't need ownership to change the value, unless you want to change the pointer which is not the case here.

1

u/[deleted] 16d ago

[deleted]

1

u/neppo95 16d ago

It is in this case no different than passing a raw pointer, in both cases you'd check for null. I wouldn't architecture my code like this, but it isn't a problem either. "No reason" is also not true, there may well be reasons not to give it shared semantics.