Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared_ptr with = symbol not allowed

Why does the below code compile

shared_ptr<parent> p(new parent);

while the below one doesn't

shared_ptr<parent> p2 = new parent;

Is there any reason for not allowing '=' symbol for shared_ptr?

Generally, if a pointer like

int *p = new int;

should be same as that of

int *p(new int);

isn't it?

like image 462
Saran-san Avatar asked Dec 13 '25 18:12

Saran-san


1 Answers

std::shared_ptr's "pointer receiving" constructor is declared explicit.

template< class Y >
explicit shared_ptr( Y* ptr );

With that, you can't use copy initialization (shared_ptr<parent> p2 = new parent;).

The best reason that I can think why std::shared_ptr's constructor is made explicit is that you would less likely to make mistakes passing a raw, unmanaged by std::shared_ptr object, to a function receiving a std::shared_ptr.

#include <memory>


void func(std::shared_ptr<int> ptr) { /* ... */}

int main() {
    auto iptr = std::make_shared<int>();
    func(iptr);  // OK
    
    /*
    int* iptr = new int;
    func(iptr);  // Unclear who would eventually manage (delete) the pointer
    // ...
    delete iptr; // Undefined behavior!
    */
}

If the constructor wasn't made explicit, then you could do the commented-out code.

Also, as what @R. Martinho Fernandes has suggested, you can have a problem if non-newed pointers are being passed.

int myint;
int* iptr = &myint;
func(iptr);  // iptr doesn't point to a newed (dynamically-allocated) object
             //   std::shared_ptr, by default, uses delete on its managed pointer
             //   if there are no more references to that pointer

Still you could do it wrong if you aren't careful when you're using two separate std::shared_ptrs to manage a raw pointer.

int* riptr = new int;
std::shared_ptr<int> iptr(riptr);
std::shared_ptr<int> iptr2(riptr); // WRONG!

With your questions about raw pointers, the two are essentially the same, but that isn't necessarily applicable to std::shared_ptr.

like image 200
Mark Garcia Avatar answered Dec 15 '25 08:12

Mark Garcia



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!