30
class MyClass {
public:
     MyClass(std::weak_ptr<MyClass> parent){}
}

i want to do this:

auto newInstance = std::make_shared<MyClass>(nullptr);

or default value of weak_ptr argument is null, such as :

void function(int arg,std::weak_ptr<MyClass> obj = nullptr);

but, what i need is to do this instead:

auto newInstance = std::make_shared<MyClass>(std::shared_ptr<MyClass>(nullptr));

why is that?

uray
  • 11,254
  • 13
  • 54
  • 74

2 Answers2

47

Because a weak_ptr in concept can only be constructed from another weak_ptr or shared_ptr. It just doesn't make sense to construct from a raw pointer, whether it's nullptr or not.

You can use a default constructed weak_ptr (std::weak_ptr<MyClass>()) where you are trying to use nullptr:

auto newInstance = std::make_shared<MyClass>(std::weak_ptr<MyClass>());
void function(int arg,std::weak_ptr<MyClass> obj = std::weak_ptr<MyClass>());
David
  • 27,652
  • 18
  • 89
  • 138
  • 12
    `nullptr` has special type `nullptr_t` so raw pointers can not be implicitly converted to `nullptr_t`. Therefore I don't see any reasons to ban `weak_ptr(nullptr)`. – magras Nov 14 '16 at 18:37
  • 2
    @magras I wrote this answer years ago, and tbh I sort of agree with you. Fundamentally it makes sense that a weak pointer need to either be associated to a shared_ptr or unassociated. The standards committee obviously decided nullptr didn't convey unassociated as well as default constructed. – David Dec 01 '16 at 19:26
  • 3
    There is also the `.reset()` member function in `std::weak_ptr` – tuket Dec 14 '20 at 14:17
-4

A weak pointer's primary purpose is usually to know whether an object that might be destroyed by other code still exists. How could a weak pointer constructed from an ordinary pointer possibly know whether the object still exists? Can you even imagine a way this could possibly work?

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • 7
    I can imagine that, I think. Quite easily. :) – Kos Jul 01 '12 at 12:39
  • "A weak pointer's sole purpose is to know whether an object that might be destroyed by other code still exists" is a bit confusing statement. I would say this is facility of weak_ptr. The purpose of smart pointers is to automate memory management. Moreover there are some more facilities of weak_ptr: (1) as you said observing object without influence on it's life time (2) preventing so called "retain cycles" (when there is a circle of objects referencing each other with shared pointer thus keeping all objects alive and causing memory leaks) (3) can refer to pointed object returning shared_ptr. – Grigori A. Jun 08 '15 at 13:07
  • 5
    How about when you want the weak_ptr to be auto-constructed to nullptr in the constructor? That's when I need this functionality. – Andrew Aug 11 '16 at 05:32