Questions tagged [weak-ptr]

std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr

Filter by
Sorted by
Tagged with
4 votes
1 answer
95 views

Create std::weak_ptr to an indexed value of an array-type std::shared_ptr?

I have a large dataset which essentially loads like this: for(int i=0;i<count; i++){ auto ptr = std::make_shared<Object>(Object()); //do stuff with ptr } This isn't great for ...
lequinne's user avatar
  • 160
1 vote
1 answer
86 views

Is it valid to static_cast 'weak_ptr<SomeThing>*' to 'void*' then back to 'weak_ptr<void>*' , or do I need to use static_pointer_cast?

I'm embedding Lua scripting in my program, and part of that is allowing Lua to manage the lifetime of some shared and weak pointers. I do that by constructing a pointer in some Lua managed memory (...
Neil Stephens's user avatar
1 vote
0 answers
83 views

C++ std::enable_if member template function overloading for template class

I'm trying to to 'overload' template function in class, depending on specialisation argument's parent template class - but it is not working(error C2938: 'std::enable_if_t<false,bool>' : Failed ...
Денис Кулаков's user avatar
0 votes
0 answers
131 views

Why is the weak reference count of a std::shared_ptr not zero after std::make_shared invoked?

After executing lines 40 and 41 below, the debugger is telling me that the weak reference count for the std::shared_ptr's a and b is 2. The ctor for Value is not storing any strong or weak references ...
wcochran's user avatar
  • 10.2k
2 votes
1 answer
104 views

Weak pointer library implementation C++

#include <iostream> using namespace std; class Printer { weak_ptr<int> m_Value{}; public: void SetValue(weak_ptr<int> p) { m_Value = p; } void Print() ...
amutamil's user avatar
4 votes
1 answer
109 views

Why is empty weak_ptr required to store null pointer, while empty shared_ptr is allowed to store non-null pointer?

Naive thinking I expected the following assertion (1) to hold true for every valid value of original argument: #include <memory> #include <cassert> void foo(std::shared_ptr<int> ...
Igor G's user avatar
  • 1,922
0 votes
2 answers
297 views

'std::bad_weak_ptr' error while using shared_from_this

Note: Before posting the question, I have gone through the existing questions on std::bad_weak_error while using shared_from_this to pass the shared_ptr of the existing shared_ptr instance to another ...
LKB's user avatar
  • 127
2 votes
1 answer
86 views

std::bad_weak_ptr after inheriting from class that inherits from std::enable_shared_from_this

I have the following piece of code: #include <memory> class A: public std::enable_shared_from_this<A> {}; struct B: public A, public std::enable_shared_from_this<B> { std::...
Rish's user avatar
  • 603
0 votes
0 answers
112 views

Can a unique_ptr be moved when referenced by a weak_ptr?

I have a bunch of unique_ptrs for database connections. They get checked out by different parts of the code to run database queries, then returned (std::move) back to the container for next use. I ...
Sean's user avatar
  • 1
1 vote
1 answer
197 views

How does std::weak_ptr store its "use_count" information?

I tried to understand the principle behind weak_ptr's implementation, especially about ref-counting. The cppreference https://en.cppreference.com/w/cpp/memory/weak_ptr says weak_ptr works as an ...
Immanuel Kant's user avatar
1 vote
3 answers
223 views

Why must the lock() function be used with a std::weak_ptr to safely extract the std::shared_ptr?

Here's an example which shows two different ways of getting a shared_ptr from a weak_ptr: #include <memory> #include <iostream> void print_shared1(std::weak_ptr <int> wp) { // ...
Peter Fletcher's user avatar
0 votes
3 answers
206 views

Make do without weak_ptr

I found an example here , about using an observer thread with an weak pointer: std::thread observer; void observe(std::weak_ptr<int> wp) { //Start observer thread observer = std::thread([wp]()...
Liviu Dorobantu's user avatar
0 votes
0 answers
71 views

How to compute hash of aliased std::weak_ptr?

Assuming a custom HashableWeakPointer as proposed in this question I would like to ask for further clarification of statements written in an answer to that question. template<class T> struct ...
JohannesWilde's user avatar
1 vote
0 answers
67 views

What's the use-case that, 2 weak_ptr share ownership while raw pointer are different? [duplicate]

I'm looking at cppreference for std::owner_less: It says: The order is such that two smart pointers compare equivalent only if they are both empty or if they share ownership, even if the values of ...
Immanuel Kant's user avatar
0 votes
2 answers
144 views

How to prove c++11 make_shared() can keep shared_ptr's control block alive even after its dtor?

My question is: is there a case that share_ptr ref count is 0, while weak_ptr ref count is not 0? Difference in make_shared and normal shared_ptr in C++ Referr this thread, showing that if a ...
Troskyvs's user avatar
  • 7,617
0 votes
0 answers
38 views

ControlBlock member of weak_ptr

So I've been reading about shared_ptr/weak_ptr implementation and I do not get a small detail. As far as I understand, there is a class ControlBlock defined in the private section of shared_ptr. But ...
Amir Mokhammed-Ali's user avatar
-2 votes
1 answer
61 views

How to not allow conversion from temporary shared_ptr to weak_ptr for derived types

I have asked this question for concrete types. The provided solution is sufficient for those, but when it comes to inheritance, it fails. Would there be a solution to that as well? Lets have a ...
Croolman's user avatar
  • 1,113
5 votes
1 answer
163 views

How to ensure a weak_ptr is not created from a temporary shared_ptr?

Let's have class Foo and method void use_weak_ptr(std::weak_ptr<Foo>). Is there a way to ensure - preferably at compile time - that the method is not called with temporary? Allow this: auto ...
Croolman's user avatar
  • 1,113
0 votes
2 answers
6k views

Capture shared_ptr in lambda

I want to capture a shared_ptr in my lambda expression. Tried two methods: Capture the shared pointer error: invalid use of non-static data member A::ptr Create a weak pointer and capture it (Found ...
Friday's user avatar
  • 23
0 votes
0 answers
76 views

Dangling pointers... Is there a another solution than std::weak_ptr?

This is more a disussion than a question, but still.. A few days ago I found myself having a big problem in my program. I'll try and be brief with the situation I encountered. My plan was to have a ...
Pedro Sarmento's user avatar
0 votes
2 answers
279 views

weak_ptr to singleton not thread-safe

I'm writing a function that returns a shared_ptr to a singleton. I want the singleton object to be destroyed when all of the references have gone away. My solution builds on this accepted answer which ...
samw's user avatar
  • 139
6 votes
2 answers
965 views

Can I reset shared_ptr without deleting object so that weak_ptr loses a reference to it

I'd like to reset a shared_ptr without deleting its object and let weak_ptr of it loses a reference to it. However, shared_ptr doesn't have release() member function for reasons, so I can't directly ...
torano's user avatar
  • 95
1 vote
1 answer
592 views

About shared_mutex and shared_ptr across multiple threads

I implemented code such that multiple instances running on different threads reads other instances' data using reader-writer lock and shared_ptr. It seemed fine, but I am not 100% sure about that and ...
torano's user avatar
  • 95
2 votes
1 answer
995 views

Calling `.lock()` on weak_ptr returns NULL shared_ptr

I am somewhat confused by the behaviour of the .lock() call on a weak_ptr. My understanding is that .lock() will return a shared_ptr of the relevant type if it has not expired otherwise it will be a ...
Paul's user avatar
  • 854
3 votes
1 answer
5k views

operator -> or ->* applied to "const std::weak_ptr" instead of to a pointer typeC/C++

In a lambda function, instead of this, I was trying to use weak_ptr to access all member function and variable, but I'm getting this error: operator -> or ->* applied to "const std::...
TheBlank's user avatar
  • 117
4 votes
1 answer
348 views

how to implement std::weak_ptr::lock with atomic operations?

I recently tried to implement an atomic reference counter in C, so I referred to the implementation of std::shared_ptr in STL, and I am very confused about the implementation of weak_ptr::lock. When ...
Leander's user avatar
  • 111
4 votes
2 answers
562 views

How to compute hash of std::weak_ptr?

So I have code that uses std::weak_ptr and maintains them in an std::set, and that works just fine -- and has worked for the last 5 or 7 years. Recently I thought I'd fiddle with using them in an std::...
Linas's user avatar
  • 773
2 votes
1 answer
185 views

Swig: simple idiomatic wrapper usage when weak_ptr are used?

note: this question is related to weak_ptr usage, but is not about wrapping weak_ptrs. I am currently evaluating Swig and I have found an "inconvenience" in the usage of the wrappers by the ...
Gabriel Devillers's user avatar
1 vote
1 answer
275 views

Why does std::weak_ptr<T>::lock return empty shared pointer here?

I'm trying to create an AABBTree structure where each node knows its parent and children. Within my AABBTreeNode class, the parent is stored as a std::shared_ptr<AABBTreeNode> and the children ...
Roland Deschain's user avatar
0 votes
1 answer
813 views

Calling a function on weak pointer

I have written the following code: #include <iostream> #include <memory> using namespace std; class Foo { int x = 0; public: int get() const { return x; } void set(int x) { ...
sunny's user avatar
  • 149
3 votes
4 answers
586 views

Mutual dependency of two objects

Quite frequently, I stuble over a situation like this: two objects need to know each other, and we have a mutual aggregation-style dependency (imagine, for example, one object handles a websocket ...
Georg P.'s user avatar
  • 2,874
2 votes
1 answer
876 views

std::weak_ptr::lock and object destruction

I know that in a multi-threading environment it's not safe to check whether an object has been fully deleted by std::shared_ptr<T>::use_count() == 0, because the object's destructor may still be ...
Donqustix's user avatar
0 votes
1 answer
117 views

How to fix this shared_ptr reference cycles?

I designed an App that holds a stack of layers and an active obj. When a Layer is attached to the App, the Layer tells App what an active object is. But my design causes a sigtrap when deallocating. ...
xubury's user avatar
  • 94
0 votes
1 answer
2k views

How to access the class member functions from a weak pointer in C++?

I am a complete newbie to smart pointers, and I have never dealt with weak_ptr in C++. I have a function in class Y, that takes in as parameter a weak_ptr of class X. Inside the function in class Y, I ...
Harini Sj's user avatar
  • 173
4 votes
1 answer
2k views

How does the ::lock() function work on std::weak_ptr?

When you have a weak_ptr, and you do: std::weak_ptr<int> wp; // Pretend it's assigned to a shared_ptr if (!wp.expired()) // Equivalent to use_count() != 0 { /* Here we're not 100% sure the raw ...
Zebrafish's user avatar
  • 12.1k
0 votes
0 answers
187 views

what is the lifetime of a shared pointer inside a constructor of an instance?

my first question: If I create a shared_ptr<class A> inside of class B constructor: class B{ public: B(){ auto a = make_shared<A>(); } }; will the owner of the object A be ...
migara's user avatar
  • 55
2 votes
1 answer
1k views

What are best use cases of shared_ptr, unique_ptr and weak_ptr?

While it is easy to learn about std::shared_ptr, std::unique_ptr and std::weak_ptr by knowing what are they, it seems to be very difficult for me to understand in what circumstances they proved to be ...
getsuha's user avatar
  • 711
2 votes
2 answers
1k views

How to give a child a weak pointer to a parent? (C++)

I've read here that, in a situation where some parent object uniquely owns several children, and each child needs to be able to access its parent, a weak pointer should be used as the back-pointer ...
user avatar
2 votes
1 answer
131 views

Usecase for weak_ptr in C++ primer 5th Edition

Hi i am reading C++ primer 5th addition and have some doubts in the section of weak_ptr. It is written that By using a weak_ptr, we don’t affect the lifetime of the vector to which a given StrBlob ...
user12002570's user avatar
  • 38.3k
1 vote
1 answer
97 views

C++: How to achieve unique ownership but non-unique thread-safe weak access

I have a class Inner that should be uniquely owned by class Outer, specifically, nobody but Outer should ever be able to destroy Inner, or keep it alive. However, I want other classes Consumers, ...
Dominic Farolino's user avatar
5 votes
2 answers
439 views

Understanding of Scott Meyers' third example of std::weak_ptr

The final example at page 137 of Effective Modern C++ draws the scenario of a data structure with objects A, B, and C in it, connected to each other via std::shared_ptr in the following way: std::...
Enlico's user avatar
  • 24k
0 votes
0 answers
94 views

How to get access to private members of other class?

I am implementing my own SharedPtr and WeakPtr and there are many methods where I need access to private members of SharedPtr from WeakPtr's methods. For example: template<typename Resource> ...
ADV's user avatar
  • 189
1 vote
2 answers
433 views

Why am I getting segmentational fault with weak_ptr

I am doing an exercise to get to know the shared pointer and weak pointer. So the example is with cyclic dependence of shared_ptr and how could I solve the problem with weak_ptr. I want to initialize ...
newstudent's user avatar
0 votes
1 answer
335 views

I can't understand weak pointers (C++) [closed]

I am trying to learn a bit about std::weak_ptr(semantics and usecases), however I cannot find many resources online. Cppreference didn't help at much, and there are a few other sites, but they didn't ...
H-005's user avatar
  • 487
0 votes
0 answers
147 views

Is there a C++ container that can handle changing hash/comparison/equality methods?

I have a class managed by std::shared_ptr. This class has a hash and all the ==, <, etc. operators. For simplicity let's say that class is int. What I want is a registry of all int's currently in ...
imMAW's user avatar
  • 173
2 votes
1 answer
152 views

Use of weak_ptr with cyclic references

So I'm having quite a hard time understanding why we have to use weak_ptr especially with cyclic reference problems, consider this code: class B; //forward declaration class A { shared_ptr<B&...
Alex's user avatar
  • 848
1 vote
1 answer
88 views

Give container ownership of its children, but have children store a reference to their parent using smart pointers

I would like to have all the children of a Node in a tree to be owned by their parent, and have each child store a reference to its parent. That way, when a parent Node is destroyed, all of its ...
Carpetfizz's user avatar
  • 8,817
5 votes
2 answers
848 views

How can I use std::enable_shared_from_this in both super and subclass?

I have two classes A and B, where B is a subclass of A. I need both classes to use std::enable_shared_from_this. I tried this: #include <memory> #include <iostream> #include <vector&...
oz1cz's user avatar
  • 5,594
3 votes
1 answer
1k views

weak_ptr obtained from weak_from_this() is invalid

Here is a minimal example to reproduce: source code: #include <memory> #include <iostream> class A : public std::enable_shared_from_this<A> { public: A(std::weak_ptr<A> ...
Artyom Gevorgyan's user avatar
3 votes
2 answers
3k views

weak_ptr, shared_ptr in lambda capture list and std::queue<T,Container>::emplace

I have a function which enqueue lambda using std::queue's build-in emplace. I created shared_ptr object (task), which later I would capture in lambda. template<typename Func, typename... Args&...
VanDyke's user avatar
  • 31

1
2 3 4 5 6