Roman Werpachowski wrote:
Is there something wrong with this code?
#include <boost/shared_ptr.hpp>
int main()
{
boost::shared_ptr<double> g(new double);
boost::shared_ptr<double> f(new double);
f = boost::shared_ptr<double>(g.get());
// You can't do this.
return 0;
}
I get a run-time memory error when I compile it with gcc. Did I do
something wrong?
g owns the first allocated double.
Then you make f also own the first allocated double.
When g and f go out of scope, both destructors delete the original
allocated double, which is undefined behaviour.
You did this to yourself, to be honest, whats wrong with:
f = g;
In the assignment, the count for the first double is decremented,
reaches 0 and it is deleted, and the count for the second double is
incremented. You then have 2 references to the second double,
accessible through f or g.
What are you trying to achieve?
Ben Pope
--
I'm not just a number. To many, I'm known as a string...