Re: ctor, operator =
From: marbac (marbac_at_chello.at)
Date: 03/19/05
- Next message: Jeff Schwab: "Re: realloc equivalent for new"
- Previous message: Casanova http://www.prashanthmohan.tk: "accessing directories using C++"
- In reply to: Andrey Tarasevich: "Re: ctor, operator ="
- Next in thread: Kurt Stutsman: "Re: ctor, operator ="
- Reply: Kurt Stutsman: "Re: ctor, operator ="
- Reply: Andrey Tarasevich: "Re: ctor, operator ="
- Reply: Ron Natalie: "Re: ctor, operator ="
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 19 Mar 2005 11:10:27 GMT
Andrey Tarasevich schrieb:
> In general case - no. Assignment operator is normally applied to the
> already constructed object and in general case the implementation of the
> assignment operator will rely on that fact. In the code above you are
> trying to apply the assignment operator to an object, which has not been
> constructed yet. Whether this is a problem in your particular case
> depends on your class implementation details.
Well i reduced my code to a simple example to show my problem.
And I also found the mistake i made ... what a mess, because
it has nothing to do with the question "
copy constructor with operator = is valid?"
thanks a lot and regards marbac
#include <iostream>
class test {
public:
test (int _size): size(_size) {
if (size>0) array=new int [this->size];
else array=0;
}
test (test& src) {
array=0; // THIS WAS MISSING!!
*this=src;
}
~test () {
if (array) delete [] array;
}
test& operator = (const test& src) {
size=src.size;
if (array) delete [] array;
if (size>0) array=new int [this->size];
else array=0;
return *this;
}
void cout_size () {
std::cout << "Size:" << size << std::endl;
}
private:
int *array;
int size;
};
int main () {
test a(4);
test b(5);
test c(6);
a.cout_size();
b.cout_size();
c.cout_size();
a=b;
a.cout_size();
test d (a); //runtime - error if deleting non 0 pointer at construction
time
d.cout_size ();
}
- Next message: Jeff Schwab: "Re: realloc equivalent for new"
- Previous message: Casanova http://www.prashanthmohan.tk: "accessing directories using C++"
- In reply to: Andrey Tarasevich: "Re: ctor, operator ="
- Next in thread: Kurt Stutsman: "Re: ctor, operator ="
- Reply: Kurt Stutsman: "Re: ctor, operator ="
- Reply: Andrey Tarasevich: "Re: ctor, operator ="
- Reply: Ron Natalie: "Re: ctor, operator ="
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|