I’m working in C++ with a C library that uses a lot of pointers in its API.
To make things work without being annoyed by memory management, I’m using extensively std::shared_ptr
and std::unique_ptr
, but when it comes to calling the internal C function, I have a bunch of get()
calls, which I find annoying.
Is there a smart way to make the compiler implicitly call the get()
function itself when it detects that the raw pointer is needed, and that a std::shared_ptr
or std::unique_ptr
is given ?
I know it can be done by writing an explicit wrapper around std::shared_ptr
like the following:
#include <iostream>
#include <memory>
template<typename T>
class SharedPtrWrapper {
public:
// Constructor
explicit SharedPtrWrapper(std::shared_ptr<T> ptr) : ptr_(ptr) {}
// Overload the dereference operator
T& operator*() const {
return *ptr_;
}
// Overload the arrow operator
T* operator->() const {
return ptr_.get();
}
// Implicit conversion to the raw pointer
operator T*() const {
return ptr_.get();
}
private:
std::shared_ptr<T> ptr_;
};
// Example usage
class MyClass {
public:
void display() const {
std::cout << "This is MyClass" << std::endl;
}
};
void functionThatNeedsRawPointer(MyClass* ptr) {
if (ptr) {
ptr->display();
}
}
int main() {
auto sharedPtr = std::make_shared<MyClass>();
SharedPtrWrapper<MyClass> wrapper(sharedPtr);
// Use the wrapper
wrapper->display(); // Access through the wrapper
functionThatNeedsRawPointer(wrapper); // Implicitly converts to raw pointer
return 0;
}
And I would like something more like the following two-liner:
template<typename T>
std::shared_ptr<T>::operator T*() {
return this->get();
}
Unfortunately it does not compile. Any idea?
Thanks in advance
Michael A. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.