[C++-sig] why does this produce a dangling reference?

FLETCHER, Shayne, FM Shayne.FLETCHER at rbos.com
Tue Mar 4 15:03:22 CET 2003


Hi All:

Here's what seems to me to be a fairly simple use case that unfortunately
suffers from the "attempt to return dangling reference" problem (using
current CVS snapshot). Can anyone help me understand what I'm doing wrong
and what I can do to overcome the problem?

class period
{};

class rate_impl{
private:
  period m_period;

public:
  virtual ~rate_impl()
  {}
  virtual period const& get_floating_frequency() const
  {
    return m_period;
  }
  virtual void generate_dates() const
  {
    period p = get_floating_frequency(); // ! causes 'dangling reference'
  }
};

struct rate_impl_wrapper : rate_impl{
  PyObject* m_self;

  rate_impl_wrapper(PyObject* self)
    : m_self(self)
  {}
  period const& get_floating_frequency() const
  {
    return boost::python::call_method(m_self
      ,"get_floating_frequency"
      , (boost::type<period const&>*)0);
  }
  period const& default_get_floating_frequency() const
  {
    return rate_impl::get_floating_frequency();
  }
  void generate_dates() const
  {
    boost::python::call_method(m_self
      , "generate_dates"
      , (boost::type<void>*)0);
  }
  void default_generate_dates() const
  {
    rate_impl::generate_dates();
  }
};

BOOST_PYTHON_MODULE(isle)
{
class_<period>("period", init<>())
  ;
class_<rate_impl
       , rate_impl_wrapper
       , boost::noncopyable>("rate_impl", init<>())
       .def("get_floating_frequency"
            , &rate_impl::get_floating_frequency
            , &rate_impl_wrapper::default_get_floating_frequency
            , return_value_policy<copy_const_reference>())
       .def("generate_dates"
         , &rate_impl::generate_dates
         , &rate_impl_wrapper::default_generate_dates)        
   ;
}

Then in Python,

import isle
rate = isle.rate_impl()
rate.generate_dates()

The end result is:

Traceback (most recent call last):
  File "test_rate.py", line 3, in ?
    rate.generate_dates()
ReferenceError: Attempt to return dangling reference to object of type:
class period

- Shayne.




********************************************************************
      Visit our Internet site at http://www.rbsmarkets.com

This e-mail is intended only for the addressee named above.
As this e-mail may contain confidential or privileged information,
if you are not the named addressee, you are not authorised to
retain, read, copy or disseminate this message or any part of it.
The Royal Bank of Scotland plc is registered in Scotland No 90312
Registered Office: 36 St Andrew Square, Edinburgh EH2 2YB
Regulated by the Financial Services Authority
********************************************************************




More information about the Cplusplus-sig mailing list