views:

409

answers:

3

I was wondering why shared_ptr doesn't have an implicit constructor. The fact it doesn't is alluded to here: http://stackoverflow.com/questions/142391/getting-a-boostsharedptr-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 */
+2  A: 

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).

Alex Lim
+2  A: 

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
A: 
int main() {

    int foo = 5;
    fun(&foo);

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

    return 0;
}