必须返回对象时,别妄想返回其reference 【Effective C++ 条款21】
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了必须返回对象时,别妄想返回其reference 【Effective C++ 条款21】,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1979字,纯文字阅读大概需要3分钟。
内容图文
![必须返回对象时,别妄想返回其reference 【Effective C++ 条款21】](/upload/InfoBanner/zyjiaocheng/632/d42caa050409436e83478786bad3a960.jpg)
class Rational { public: Rational(int numerator = 0, int denominator = 1) : n(numerator), d(denominator) { printf("Rational Constructor\n"); } ~Rational() { printf("Rational Destructor\n"); } Rational(const Rational& rhs) { this->d = rhs.d; this->n = rhs.n; printf("Rational Copy Constructor\n"); } private: int n, d; friend const Rational operator*(const Rational& lhs, const Rational& rhs); };
Rational的*运算符可以这样重载:
const Rational operator*(const Rational& lhs, const Rational& rhs) { Rational tmp(lhs.n * rhs.n, lhs.d * rhs.d); return tmp; }
但是不可以这样重载:【区别在于一个&】
const Rational& operator*(const Rational& lhs, const Rational& rhs) { Rational tmp(lhs.n * rhs.n, lhs.d * rhs.d); return tmp; }
当这样去使用:
Rational x(1, 2), y(2, 3); Rational z = x * y;
第一种方法可以得到正确的结果,因为会调用Rational的拷贝构造函数将tmp赋给z,但是第二种方法返回的是tmp的引用,在函数退出前,tmp就被销毁了,所以这样做是不对的。
不过,第一种方法虽然功能上没有问题,但是效率上有所欠缺,因为调用了三次构造函数,一次复制构造函数,一次析构函数
Rational Constructor Rational Constructor Rational Constructor Rational Copy Constructor Rational Destructor
可以进行返回值优化如下:
const Rational operator*(const Rational& lhs, const Rational& rhs) { return Rational(lhs.n * rhs.n, lhs.d * rhs.d); }
Rational Constructor Rational Constructor Rational Constructor
优化之后少调用了一次复制构造函数和析构函数
完整代码如下:
#include <stdio.h> class Rational { public: Rational(int numerator = 0, int denominator = 1) : n(numerator), d(denominator) { printf("Rational Constructor\n"); } ~Rational() { printf("Rational Destructor\n"); } Rational(const Rational& rhs) { this->d = rhs.d; this->n = rhs.n; printf("Rational Copy Constructor\n"); } private: int n, d; friend const Rational operator*(const Rational& lhs, const Rational& rhs); }; const Rational operator*(const Rational& lhs, const Rational& rhs) { return Rational(lhs.n * rhs.n, lhs.d * rhs.d); } int main() { Rational x(1, 2), y(2, 3); Rational z = x * y; return 0; }
内容总结
以上是互联网集市为您收集整理的必须返回对象时,别妄想返回其reference 【Effective C++ 条款21】全部内容,希望文章能够帮你解决必须返回对象时,别妄想返回其reference 【Effective C++ 条款21】所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。