5

I was wondering why shared_ptr doesn't have an implicit constructor. The fact it doesn't is alluded to here: Getting a boost::shared_ptr for this

(I figured out the reason but thought it would be a fun question to post anyway.)

#include <boost/shared_ptr.hpp>
#include <iostream>

using namespace boost;
using namespace std;

void fun(shared_ptr<int> ptr) {
    cout << *ptr << endl;
}

int main() {
    int foo = 5;
    fun(&foo);
    return 0;
}

/* shared_ptr_test.cpp: In function `int main()':
 * shared_ptr_test.cpp:13: conversion from `int*' to non-scalar type `
 *  boost::shared_ptr<int>' requested */
Community
  • 1
  • 1
cdleary
  • 69,512
  • 53
  • 163
  • 191

5 Answers5

10

In this case, the shared_ptr would attempt to free your stack allocated int. You wouldn't want that, so the explicit constructor is there to make you think about it.

cadabra
  • 384
  • 3
  • 8
6

The logical reason is that:

  • calling the delete operator is not implicit in C++
  • the creation of any owning smart pointer (shared_whatever, scoped_whatever, ...) is really a (delayed) call to the delete operator
curiousguy
  • 8,038
  • 2
  • 40
  • 58
2

Long time lurker, and a 3rd year soft eng student here, Haphazard guess would be, to stop you from attempting to convert a 'natural' pointer to a shared_ptr, then deallocing the pointed object, without the shared_ptr knowing about the dealloc.

(Also, reference counting problems blah blah).

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
Alex Lim
  • 589
  • 1
  • 8
  • 10
-1
int main() {

    int foo = 5;
    fun(&foo);

    cout << foo << endl; // ops!!

    return 0;
}
Evan Teran
  • 87,561
  • 32
  • 179
  • 238
user35978
  • 2,302
  • 1
  • 13
  • 14
-3

I think there is no reason to have explicit in this constructor.

Mentioned examples with incorrect using of offset address operator (&) make no sense since there is no place to use such operator in modern C++. Except only such idiomatic code in assignment/comparision operator as 'this == &other' and maybe some test code.

V_V
  • 612
  • 9
  • 23
  • @vBx: in mentioned example [1](http://stackoverflow.com/questions/304093/why-shared-ptr-has-an-explicit-constructor/304183#304183) offset address operator (&) has been used to pass parameter by pointer to function. Should use reference instead. – V_V Jun 04 '11 at 10:19
  • `operator&` gives the address, not the "offset" (whatever that means) of a lvalue. – curiousguy Oct 07 '11 at 14:34