Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: what exactly does std::remove_pointer do?

Tags:

c++

I have encountered the following line:

std::weak_ptr<std::remove_pointer<decltype(myPublisher.get())>::type> captured_pub = myPublisher;

I assume that "remove_pointer" removes the pointer and returns the object itself but that's only an assumption. And this is done to eventually point the object with a weak_ptr?

I was trying to understand what "remove_pointer" does, but couldn't find a satisfied explanation. Can someone explain this line of code?

like image 852
Yaniv G Avatar asked Apr 28 '26 12:04

Yaniv G


1 Answers

Working from the inside out:

  • myPublisher must be a variable of type std::shared_ptr<T> (where T is some unknown type in this case). myPublisher.get() thus returns a T* pointer variable that points to some T object that the shared_ptr shares ownership of.

  • decltype(...) returns the type of the variable/expression it is given. In this case, the return value of get(), thus it returns the T* type.

  • std::remove_pointer<...>::type removes the * from the specified type. In this case, returning the T type.

  • std::weak_ptr<...> is then declared with that type as its template argument. In this case, std::weak_ptr<T>.

So, for example, let's say T is some class named Publisher, so myPublisher is an object of type std::shared_ptr<Publisher>, and so myPublisher.get() returns a Publisher* pointer, so captured_pub is a std::weak_ptr<Publisher>.

  std::weak_ptr<std::remove_pointer<decltype(myPublisher.get())>::type> captured_pub = myPublisher;
= std::weak_ptr<std::remove_pointer<decltype(Publisher*)>::type> captured_pub = myPublisher;
= std::weak_ptr<std::remove_pointer<Publisher*>::type> captured_pub = myPublisher;
= std::weak_ptr<Publisher> captured_pub = myPublisher;

Another way to determine T would be to simply use the shared_ptr::element_type member instead, eg:

std::weak_ptr<decltype(myPublisher)::element_type> captured_pub = myPublisher;

Or, simply let the compiler deduce weak_ptr's template argument based on the type of shared_ptr being assigned to it, eg:

std::weak_ptr captured_pub = myPublisher;
like image 73
Remy Lebeau Avatar answered Apr 30 '26 00:04

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!