|
Boost Users : |
From: Nat Goodspeed (nat_at_[hidden])
Date: 2007-10-04 16:56:22
Robbie Morrison wrote:
> class MyClass
> {
> public:
> MyClass (int& i) // & indicates pass-by-reference
> : d_int(&i) { } // & is address-of operator
> ~MyClass() { std::cout << "destroying a MyClass" << std::endl; }
> private:
> boost::shared_ptr<int> d_int; // shared pointer FAILS
> // int* d_int; // raw pointer works
> };
>
> int main()
> {
> int myint(2); // simple integer
> MyClass myclass(myint); // constructor call
Here's your problem. boost::shared_ptr is designed to manage heap
(new/delete) storage, not auto storage. When a shared_ptr's destructor
determines that it was the last shared_ptr to a given heap block, it
executes 'delete (wrapped pointer)'. So in effect, you've written:
int myint(2); // auto int lives on stack
delete &2; // trying to delete from heap
A far more typical design for MyClass would accept a
boost::shared_ptr<int> as the ctor parameter. You'd allocate your int
(or whatever) on the heap, immediately capturing it in a shared_ptr and
never again referring to it with a plain dumb pointer.
(in MyClass):
MyClass(boost::shared_ptr<int> i): d_int(i) {}
(in main()):
MyClass myclass(new int(2));
or
boost::shared_ptr<int> myint = new int(2);
MyClass myclass(myint);
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net