[C++-sig] virtual functions returning const char

Aaron Bentley abentley at panoramicfeedback.com
Mon Jan 24 19:44:58 CET 2005

I've encountered a problem wrapping virtual functions that return const 
char *.  I get ReferenceError: Attempt to return dangling pointer to 
object of type: c

Here's my example code (adapted from the tutorial):

struct Base
    virtual const char * f(){return "fee";}

struct BaseWrap: Base
    BaseWrap(PyObject* self_)
    const char *f() { return call_method<const char *>(self, "f"); }
    const char *default_f() {return Base::f();}
    PyObject *self;

const char *call_f(Base &b)
    return b.f();

    class_<Base, BaseWrap, boost::noncopyable>("Base")
       .def("f", &Base::f, &BaseWrap::default_f)

    def ("call_f", call_f);

Finally, in Python:
         class Derived(Base):
             def f(self):
                 return "foo"

         d = Derived()
         assert(d.f() == "foo")
         assert(call_f(d) == "foo")

         b = Base()
         assert(b.f() == "fee")
         assert(call_f(b) == "fee")

         assert(Base().f() == "fee")
         b = Base()
         #all lines except this one pass
         assert(call_f(b) == "fee")

All assertions except the last one pass.  That is they pass
1. If I'm calling from Python or
2. If the default virtual function is not invoked.

But if I invoke the default virtual function from C++, I get the 
dangling pointer exception.

I don't really understand the problem, since string literals like "fee" 
should have a permanent location in memory.

Aaron Bentley
Director of Technology
Panometrics, Inc.

More information about the Cplusplus-sig mailing list