[C++-sig] Polymorphism and Dangling Reference exception

Garrick Chin nonexistent.ftp at gmail.com
Thu May 18 21:12:35 CEST 2006


Hello all, I am trying to run a basic polymorphism test for
boost::python using the following simple code:

polymorphism_test.cpp:

struct Shape
{
    virtual ~Shape() {}

    virtual std::string draw(const std::string& param) = 0;
};

struct ShapeWrap : Shape, wrapper<Shape>
{
    std::string draw(const std::string& param)
    {
        return this->get_override("draw")(param);
    }
};

std::string printShape(Shape* shape)
{
    return shape->draw("blah");
}

BOOST_PYTHON_MODULE(test)
{
    class_<ShapeWrap, boost::noncopyable>("Shape")
        .def("draw", pure_virtual(&Shape::draw))
        ;

    def("printShape", &printShape);
}

polymorphism_test.py:

import test

class Circle(test.Shape):
    def draw(self, param):
        return "circle: " + param

print test.printShape(Circle())

When the Python interpeter hits the "print test.printShape(Circle())"
line, it throws the following exception:

ReferenceError: Attempt to return dangling reference to object of
type: class std::basic_string<char,struct std::char_traits<char>,class
std::allocator<char> >

I do not understand why this would be thrown.  I am not returning any
references or pointers, and I basically copied this code from the
documentation.  What would be causing this exception?  Thank you for
your time.



More information about the Cplusplus-sig mailing list