[C++-sig] how to handle bare references with a shared_ptrHeldType

Gregory Price price at ELLINGTON.com
Mon Sep 26 19:52:40 CEST 2005


David Abrahams wrote:
> > OTOH, if you use return_internal_reference, BP should know that 
> > creating a
> > shared_ptr with a refcount of 1 is evil..  is that really 
> what it does?
> 
> No, that's not what it does.  When you use 
> return_internal_reference it creates a Python object holding 
> the C++ object with a raw pointer. Isn't that in the documentation?

That's good news.

But I'm puzzled how that can be.
Perhaps it'd be clearer if you explain how
the following code can work:

----- begin test.cpp -----
#include <boost/shared_ptr.hpp>
#include <boost/python.hpp>

using namespace boost::python;

struct A {
  int x;
};

int
get_x(boost::shared_ptr<A> a)
{
  return a->x;
}

A&
make_A(int x)
{
  static A a;
  a.x = x;
  return a;
}

BOOST_PYTHON_MODULE(test)
{
  class_<A, boost::shared_ptr<A> >("A");
  def("get_x", &get_x);
  def("make_A", &make_A, return_internal_reference<>());
}
----- end test.cpp -----

  $ python
  >>> from test import make_A, get_x
  >>> a = make_A(3)
  >>> get_x(a)
  3

Here I use return_internal_reference on make_A;
so I should get a Python object "a" holding the C++ A
as a raw pointer.  But there's no trouble passing "a"
to get_x, which wants a shared_ptr<A>.
What is Boost.Python doing that makes this work?


Thanks for your help and patience.

Greg

=============================================================================================
Email transmissions can not be guaranteed to be secure or error-free, as information 
could be intercepted, corrupted, lost, destroyed, arrive late or incomplete, or contain 
viruses.  The sender therefore does not accept liability for any errors or omissions in 
the contents of this message which arise as a result of email transmission.  In addition,
the information contained in this email message is intended only for use of the 
individual or entity named above.  If the reader of this message is not the intended
recipient, or the employee or agent responsible to deliver it to the intended recipient,
you are hereby notified that any dissemination, distribution, or copying of this communication,
disclosure of the parties to it, or any action taken or omitted to be taken in reliance on it,
is strictly prohibited, and may be unlawful.  If you are not the intended recipient please
delete this email message. 
==============================================================================================




More information about the Cplusplus-sig mailing list