c++为什么这里没有调用两次拷贝够造函数

楚江课的救赎 2013-04-08 11:10:30
/*
* File: main.cpp
* Author: chujiangke
*
* Created on 2013年4月1日, 下午11:04
*/

#include <cstdlib>
#include <iostream>
using namespace std;

/*
*
*/
class point
{
int a;
int b;
//point(point&);
public:
point(int b,int a){cout<<"contructor with argc"<<endl;this->a=a;this->b=b;}
point(){cout<<"contructor without argc "<<endl;a=0;b=0;}
point &operator=(const point a){cout<<"copy whit ="<<endl;this->a=a.a;this->b=a.b;return *this;}
point(const point &obj){cout<<"copy contructor"<<endl;a=obj.a;b=obj.b;}
int get_a(){return a;}
int get_b(){return b;}
};

point funciton1(point a)
{
point *b=new point;
cout<<"11111111111111111"<<endl;
*b=a;
cout<<"22222222222222222"<<endl;
return *b;

}
int main(int argc, char** argv) {

point a(11,12);
point b;
b=funciton1(a);
cout<<",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,:"<<endl;
point c=funciton1(a);
cout<<b.get_a();
return 0;
}


contructor with argc
contructor without argc
copy contructor
contructor without argc
11111111111111111
copy contructor
copy whit =
22222222222222222
copy contructor
copy whit =
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,:
copy contructor
contructor without argc
11111111111111111
copy contructor
copy whit =
22222222222222222
copy contructor//function构造临时变量要一次,初始化c也要一次拷贝啊
12
...全文
251 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Hi幸福来敲门 2013-04-15
  • 打赏
  • 举报
回复
ayrb13 2013-04-09
  • 打赏
  • 举报
回复
貌似说错了。。。。。
ayrb13 2013-04-09
  • 打赏
  • 举报
回复
先给楼主纠正一个小问题吧。 point &operator=(const point a){cout<<"copy whit ="<<endl;this->a=a.a;this->b=a.b;return *this;} 这行代码传入参数最好是const point& a。 如果你想说的是b和c构造的不同之处: b=function1(a) function1返回值传入operator=,因为你传的是值,非引用,这里有一个copy constructor 然后是copy with 这个是没问题的。 point c =function1(a)等价于point c(function1(a)) 肯定只有一次啦 当一个函数调用另一个函数返回值的时候,只有当返回值和传入类型均为引用时,才不会引起拷贝构造。 当返回值或传入类型为值类型时会有一次拷贝构造,当返回值和传入类型均为值类型时同样只会有一次拷贝构造。
dahaiI0 2013-04-08
  • 打赏
  • 举报
回复
谷歌“返回值优化”,More Effceive C++上也有讲到。

1,075

社区成员

发帖
与我相关
我的任务
社区描述
硬件/嵌入开发 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧