- #1
ChrisVer
Gold Member
- 3,378
- 464
I have written the following class:
When I run the code, I see something "weird": for each assignment operation I get a message:
Object copied
Object destroyed
After some investigation I found that the reason this happens is because in the assignment operator overload I pass the rhs as a value, so it's copied rhs, and when the assignment is over and gets out-of-scope the copy gets destroyed. I was wondering though, is it possible to avoid copying the object (can be slow)? I'm askinng because I read here that passing-by-reference is not exception safe...
http://www.cplusplus.com/articles/y8hv0pDG/
if not is it right to say that the operator = is doomed to be slower than copying the object as
?
Code:
class Rectangle{
private:
double length;
double height;
const char* name;
public:
Rectangle (){};
Rectangle (double l, double h, const char* n) : length(l), height(h), name(n) {};
//copy constructor
Rectangle ( const Rectangle & r) {
cout<<"Copying Rectangle Object : "<<endl;
length=r.length;
height=r.height;
};
virtual ~Rectangle(){ cout<<"Rectangle object destroyed"<<endl; };
//getters-setters
void setLength(double x) {length=x;};
void setHeight(double x) {height=x;};
double getLength() const {return length;};
double getHeight() const {return height;};
void Print() const{
cout<<"You have a Rectangle Object"<<endl;
cout<<"\tHeight : "<<height<<endl;
cout<<"\tLength : "<<length<<endl;
}
;
//operator overloading
Rectangle& operator=(Rectangle rhs){
//swap with copied rhs
std::swap(length, rhs.length);
std::swap(height, rhs.height);
return *this;
};
};
int main(){
Rectangle r(5.2,5.1);
r.Print();
Rectangle r8;
r8 = r;
r8=r8;
r8.Print();
system("PAUSE");
return 0;
}
When I run the code, I see something "weird": for each assignment operation I get a message:
Object copied
Object destroyed
After some investigation I found that the reason this happens is because in the assignment operator overload I pass the rhs as a value, so it's copied rhs, and when the assignment is over and gets out-of-scope the copy gets destroyed. I was wondering though, is it possible to avoid copying the object (can be slow)? I'm askinng because I read here that passing-by-reference is not exception safe...
http://www.cplusplus.com/articles/y8hv0pDG/
if not is it right to say that the operator = is doomed to be slower than copying the object as
Code:
Rectangle r8(r);