复制construtor称为额外 [英] copy construtor called extra
问题描述
我有一个程序显示奇怪的行为
I have a program which is showing weird behaviour
#include <cstdlib>
#include <iostream>
using namespace std;
class man{
int i ;
public:
man(){
i=23;
cout << "\n defaul constructir called\t"<< i<<"\n";
}
man (const man & X) {
i = 24;
cout << "\n COPY constructir called\t"<< i<<"\n";
}
man & operator = (man x ) {
i = 25;
cout << "\n = operator called\t"<< i<<"\n";
return *this;
}
};
int main(int argc, char *argv[])
{
man x;
cout <<"\n ----------\n";
man y = x;
cout <<"\n ----------\n";
x=y;
return 0;
}
defaul constructir called 23
----------
COPY constructir called 24
----------
COPY constructir called 24
= operator called 25
这个输出对x = y的第三次调用很奇怪;
This output is weird for the third call of x=y ;
为什么当我没有创建一个新对象而是使用旧对象时,会调用一个额外的副本打印。
Why is there an extra print of copy construtor called when I did not made a new object but am working with old objects .
这是因为两者之间的临时对象,如果是,我可以在这里停止....
Is it becuase of temporary objects in between and if yes can i stop them here ....
推荐答案
man& operator =(man x);
您的参数通过 - 值接受其参数,将调用复制构造函数。这就是造成额外不必要的电话。通过引用传递参数将避免一个副本,但是你将不能通过临时(通常称为右值):
Your parameter takes its argument by-value, and when that happens it will invoke the copy-constructor. That's what's causing the extra unwanted call. Passing your argument by reference will avoid a copy, but then you will not be able to pass temporaries (commonly referred to as rvalues):
struct man
{
man& operator =(man& x) { return *this; };
};
int main()
{
man a, b;
a = b; // works
a = man(); // error: no viable overloaded '=',
// expected an l-value for 1st argument
}
通过引用 const
将允许复制lvalue和rvalues:
Passing by reference to const
will allow the copy-construction of both lvalues and rvalues:
man& operator =(man const& x);
// ^^^^^
这篇关于复制construtor称为额外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!