Re: reference of boost::shared_ptr instead of Handle

Posted by Luigi Ballabio on
URL: http://quantlib.414.s1.nabble.com/reference-of-boost-shared-ptr-instead-of-Handle-tp7623p7632.html

On Fri, 2009-09-04 at 10:19 +1000, Yan Kuang wrote:
> In this example, I can use reference so that the second f.check()
> print 2.

Yes, but storing references is dangerous, because you can't control
lifetime (which is kind of the whole point of smart pointers, anyway.)

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

class T {
    int i_;
  public:
    T(int i) : i_(i) {}
    int i() const { return i_; }
};

class Foo {
    boost::shared_ptr<T> & p_;
  public:
    Foo(boost::shared_ptr<T>& p) : p_(p) {}
    void check() const {
        std::cout << p_->i() << std::endl;
    }
};

Foo make_foo() {
    boost::shared_ptr<T> p(new T(1));  // local to the function
    Foo f(p);  // stores a reference to the local variable...
    return f;
    // ...but here, the local variable is destroyed.
}

int main() {
    Foo f = make_foo();
    // now f is storing a reference to a deleted object.
    f.check();  // all bets are off. This might crash the program,
                // print garbage (it prints 0 on my Linux box),
                // or even print the right value. But it's unreliable.
    return 0;
}


--

All generalizations are false, including this one.
-- Mark Twain



------------------------------------------------------------------------------
Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day
trial. Simplify your report design, integration and deployment - and focus on
what you do best, core application coding. Discover what's new with
Crystal Reports now.  http://p.sf.net/sfu/bobj-july
_______________________________________________
QuantLib-users mailing list
[hidden email]
https://lists.sourceforge.net/lists/listinfo/quantlib-users