[vdr] Problem with cChannel's copy constructor
Martin Cap
macap20001 at compuserve.de
Thu Aug 4 18:45:12 CEST 2005
Marcel Wiesweg wrote:
> ....
> It seems these two are not used in VDR except for one place (where I found
> this), cSectionHandler::SetChannel. The value stored by cSectionHandle has
> nid,tid,sid set to 0.
> In the line
> shp->channel = Channel ? *Channel : cChannel();
> there seems only the operator= involved, but actually the copy constructor is
> invoked before the *Channel is given to opertator=.
> Attached is a short test program which illustrates the problem.
>
> Solution is to make the copy constructor do copying.
>
Hi,
first thing, in your code, you should return *this in the operator= (and
check if &a equals 'this'), which, I assume, you just
forgot.
Now what the compiler does, is the following :
Assume this snippet from your code :
...
1: A *pointer= &object;
2: A second;
...
3: second = pointer ? *pointer : A();
@3: The compiler creates a anonymous, automatic object for class A on
compile-time and copies members from *pointer via its copy-constructor
into it (setting d=0!). Then, the operator= gets called for second with
the temporary object as an argument (hence, copying d=0 into second).
Try the attached code, which'll make it clearer, I presume...
Apparently, the copy-constructor in cChannel needs explanation...
--
---
Regards,
Martin Cap
-------------- next part --------------
#include <stdio.h>
#include <iostream>
using std::cerr;
using std::endl;
class A {
public:
A() {
cerr << __PRETTY_FUNCTION__ << " of " << this << endl;
d=0;
}
//Define a copy constructor that does not copy
A(const A &a) {
if(this == &a)
return;
cerr << __PRETTY_FUNCTION__ << " of " << this << " with " << &a << endl;
//cChannel's constructor does this:
d=0;
//Should be:
//d=a.d;
}
A& operator=(const A &a) {
cerr << __PRETTY_FUNCTION__ << " of " << this << " with " << &a << endl;
if(this == &a)
return *this;
d=a.d;
return *this;
}
int d;
};
int main() {
A object;
object.d=5;
A *pointer= &object;
A second;
cerr << "A object is " << &object << ", A *pointer is " << &*pointer << ", A second is " << &second << endl;;
//Now trying to assign object to second. Should result in copying.
//this assignment is done in sections.c:143
second = ((&*pointer) ? *pointer : A());
printf("Value of second's d is: %d\n\n", second.d);
//no difference without the redirection BTW
second = ((&*pointer) ? object : A());
//Value of d is 0, should be 5
printf("Value of second's d is: %d\n", second.d);
return 0;
}
More information about the vdr
mailing list