While Guilherme Ferreira's answer elaborates on template argument deduction (and is correct in that regard), I believe this is not the answer you're looking for.
I'm trying to pass a pointer to a stack variable to a function (I don't control) that only takes a boost::shared_ptr.
shared_ptr
means shared ownership over the pointed object. If the function you're trying to call saves the pointer in some of its data structures, like a container, and then returns, the pointer will become dangling as soon as the value on the stack is destroyed, despite the fact that shared_ptr
still holds a reference. In order to do what you want, you have to be absolutely sure that the function does not save the pointer anywhere and can only use it during this one call.
Provided that this condition is fulfilled, you can create a shared_ptr
pointing to a value on the stack, but you can't use make_shared
for that. make_shared
allocates a new object on heap, along with a reference counter for it, and initializes it with the arguments you passed to the function call. The returned shared_ptr
points to that new object and not to the object on the stack.
void foo()
{
int n = 10;
boost::shared_ptr< int > pn = boost::make_shared< int >(n);
assert(*pn == 10); // succeeds
assert(pn.get() == &n); // fails
bar(pn);
}
This implies that modifications bar
makes to the pointed int
are not reflected on n
.
In order to create a shared_ptr
to an existing object, you have to use its constructor directly. Also, since the object's lifetime is controlled by the stack, you have to prohibit shared_ptr
from destroying the object. This can be done by specifying a no-op deleter on shared_ptr
construction.
void foo()
{
int n = 10;
boost::shared_ptr< int > pn(&n, boost::null_deleter());
assert(*pn == 10); // succeeds
assert(pn.get() == &n); // succeeds
bar(pn);
}
Note, however, that this code still allocates heap memory for the reference counter shared_ptr
uses, so you're not winning any performance.