[C++-sig] Re: Exposing copy constructors with Boost::Python
David Abrahams
dave at boost-consulting.com
Thu Jul 22 14:48:11 CEST 2004
Christopher Dawson <dawson at physics.uq.edu.au> writes:
> Apologies if this is a common problem with a common solution, but I
> haven't been able to find it anywhere.
>
> I have a simple class which stupidly has a c-style array as a member:
Your class has a pointer as a member, not an array.
> class Test {
> public:
> int *a;
>
> Test(int N) {
> a = new int[N];
> }
>
> Test(const Test& T) {
> a = new int[T.N];
^^
?? There is no N member of Test??
Your copy ctor doesn't copy the contents of the array. Intentional?
> }
>
> Test& operator=(const Test& T) {
> if (N != T.N) {
> delete[] a;
> a = new int[N];
> for (int i=0;i<N;i++)
> a[i] = T.a[i];
> }
> }
> ~Test() {
> if (a)
> delete[] a;
> }
> };
>
> I have wrapped this with Boost::Python (1_31_0), and understood that
> the copy and assignment constructors would be wrapped automatically.A
>
> However copying the object from Python
What do you mean by "copying the object from Python"?
> just copies the pointer, not
> the array. I can explicitly expose the copy constructor with
>
> .def(init<const Test&>())
>
> so it's possible to do
>
> a = Test(4)
> b = Test(a),
>
> but I'd like to be able to to
>
> b = a
When you do that in Python, it *always* just rebinds the reference
that B was referring to so b and a are "pointing at" the same object.
Nothing ever gets copied. There's no way to change that; it's just
the way Python works.
> Have I missed something about exposing copy constructors?
Forget about Python for a moment; it looks to me like you've missed
something about writing copy ctors in C++.
Don't you want this C++ to work
Test x[2];
x.a[0] = 1;
x.a[1] = 2;
Test y = x;
assert(y.a[0] == x.a[0]);
assert(y.a[1] == x.a[1]);
??
--
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com
More information about the Cplusplus-sig
mailing list