-1

The fifth edition of c++ primer describes weak_ptr like this:

A weak_ptr is a smart pointer that does not control the lifetime of the object to which it points.Instead,a weak_ptr points to an object that is managed by a shared_ptr.

But why dot operators are used instead of -> when operations such as reset, use_count, and lock are called? For example:

weak_ptr<int> w(sp);
w.use_count();
w.lock();

Can someone tell me where the problem is?

gaofeng
  • 393
  • 1
  • 3
  • 11
  • 4
    Because a `weak_ptr`, like `shared_ptr` and `unique_ptr`, *isn't* a pointer. It's just a regular object with overloads of `operator *` and `operator ->`. You use `*` and `->` to access the underlying object, `.` to access the `_ptr` itself. – molbdnilo Mar 21 '23 at 07:17
  • 1
    `std::weak_ptr` does not overload the `*` and `->` operators. You have to first `lock()` it to access its associated `std::shared_ptr`, and then you can use `*`/`->` on that instead. – Remy Lebeau Mar 21 '23 at 07:23
  • 2
    `w` is not a pointer, its an object, an instance of a std::weak_ptr class. As such it has normal member functions that can be called like any other member function of any other object. See e.g. [this std::weak_ptr reference](https://en.cppreference.com/w/cpp/memory/weak_ptr) for more information. And as mentioned, it doesn't even have overloaded access operators itself, so can't even be used as a "pointer". – Some programmer dude Mar 21 '23 at 07:27
  • 3
    Yesterday, you asked almost the [same question about unique_ptr](https://stackoverflow.com/questions/75789814/can-unique-ptr-point-to-a-normal-pointer). If you need to ask a question here for every other line, maybe C++ Primer doesn't do it for you. I've seen it happen that some (good) books and some (equally good) people just don't go together. Think about getting another [book from the list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Friedrich Mar 21 '23 at 07:47

1 Answers1

6

std::weak_ptr is a class type, and like any class the . operator is used to access its members via a non-pointer instance of that class.

However, unlike other smart pointer classes, std::weak_ptr does not have an operator-> (or operator*) defined to access the object it refers to. You have to first lock() it to gain access to its associated std::shared_ptr, which has those operators defined to access the referred object.

Jason
  • 36,170
  • 5
  • 26
  • 60
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770