引言

在条目20中,我们知道了值传递和引用传递的效率问题,因此在设计程序时,我们可能就尽可能来返回引用而不是值。

可是,可能会犯下面的一些错误:传递一些引用指向其实并不存在的对象。

第一节:返回临时变量的引用

假如我们有以下的例子,先看值传递

 class A {
public:
A(int n = , int d = ):n(n),d(d) {}
private:
int n,d;
friend const A operator* (const A& l, const A& r);
};

在operator*系以值传递的方式返回了一个计算结果,联系到条款20,我们自然会想到,那么用引用传递试试。

因为函数返回的是A对象,所以函数创建新对象的方式有2:

1.在stack空间创建

 const A& operator* (const A& l, const A& r) {
A result(l.n * r.n, l.d * r.d);
return result;
}

这样我们避免值传递的调用构造和析构函数,可是result是个临时变量,在函数推出前就被销毁了。任何对这个函数的调用都会是无意义的行为。

2.在heap空间创建

 const A& operator* (const A& l, const A& r) {
A* result = new A(l.n * r.n, l.d * r.d);
return *result;
}

这样解决了上面临时变量的问题。可是,这个new出来的对象什么时候被释放呢?

就算我们调用A的时候很谨慎,但还是避免不了出错,比如

 A w,x,y,z;
w = x * y * z; // 实际与operator*(operator*(x, y), z)相同

这里同一个语句例调用了两次operator*,因此两次使用new,也就需要两次delete,但却没有合理的办法让operator*使用者进行那些delete调用。这就会导致资源泄露。

经过上面两种方法都不行,可能你还会想到这种方法:我声明一个static对象不行么?

比如:

 const A& operator* (const A& l, const A& r) {
static A result;
result = .....
return result;
}

看上去完美的解决了这个问题,那么我们这样使用的时候呢?

 bool operator == (const A& l, const A& r);
A a,b,c,d;
if ((a*b) == (c*d)) {
....
}

结果就会出现:(a*b) == (c*d)总是为true,无论a,b,c,d是什么!

将(a*b) == (c*d)拆开来理解,我们就可以知道为什么了。

operator == (operator*(a, b), operator(c*d));

因为到最后位置,都会返回static对象的现值,也就不怪乎为什么返回true了。

◆总结

1.绝不要返回pointer或者referenc指向一个local stack对象,或返回reference指向一个heap-allocated对象,或返回pointer或reference指向一个local static对象。

[Effective C++ --021]必须返回对象时,别妄想返回其reference的更多相关文章

  1. EC笔记:第4部分:21、必须返回对象时,别返回引用

    使用应用可以大幅减少构造函数与析构函数的调用次数,但是引用不可以滥用. 如下: struct St { int a; }; St &func(){ St t; return t; } 在返回t ...

  2. 条款21: 必须返回对象时,不要强行返回对象的reference

    总结: 绝不要返回一个local栈对象的指针或引用:绝不要返回一个被分配的堆对象的引用:绝不要返回一个静态局部对象(为了它,有可能同时需要多个这样的对象的指针或引用). 条款4中给出了“在单线程环境中 ...

  3. 【21】必须返回对象时,别妄想返回器reference

    1.考虑有理数Rational,有个友元操作符*,返回Rational对象.返回对象,导致临时对象的构造,析构.效率低,因此会想返回方法内局部对象的引用,这种方法不可行.为什么? 2.调用方法是在st ...

  4. Effective C++ -----条款21:必须返回对象时,别妄想返回其reference

    绝不要返回pointer或reference指向一个local stack对象,或返回reference指向一个heap-allocated对象,或返回pointer或reference指向一个loc ...

  5. 必须返回对象时,别妄想返回其reference 【Effective C++ 条款21】

    class Rational { public: Rational(, ) : n(numerator), d(denominator) { printf("Rational Constru ...

  6. 条款21:必须返回对象时,别妄想返回其reference(Don't try to return a reference when you must return an object)

    NOTE: 1.绝不要返回pointer或reference 指向一个local stack 对象,或返回reference 指向一个heap-allocated对象,或返回pointer 或refe ...

  7. C++ 函数返回对象时并没有调用拷贝构造函数

    #include <iostream> #include <vector> #include <string.h> using namespace std; cla ...

  8. Effective C++ -----条款12: 复制对象时勿忘其每一个成分

    Copying函数应该确保复制“对象内的所有成员变量”及“所有base class成分”. 不要尝试以某个copying函数实现另一个copying函数.应该将共同机能放进第三个函数中,并由两个cop ...

  9. 读书笔记_Effective_C++_条款二十一:当必须返回对象时,别妄想返回其reference

    在栈空间的临时成员变量在函数生命期结束后无法传出 friend A& operator*(const A& a, const A& b) { A temp; temp.data ...

随机推荐

  1. Java [leetcode 21]Merge Two Sorted Lists

    题目描述: Merge two sorted linked lists and return it as a new list. The new list should be made by spli ...

  2. virtualbox中ubuntu和windows共享文件夹设置

    系统平台:win8.1.virtualbox4.3.8.ubuntu12.041.安装VBoxGuestAdditions_4.3.8.iso增强工具,安装完毕后根据提示重启Ubuntu,具体操作如下 ...

  3. create a C# context menu from code

    I try the one of your approach, it works well in my computer. Below is my code: public void AddConte ...

  4. NGINX(一)内存结构

    ngx_buf_t和ngx_chain_t是nginx中操作内存的重要手段, 很多的数据都需要通过这个结构进行保存. 其中ngx_buf_t中保存一块可用内存, ngx_chain_t则是将内存块连接 ...

  5. Spring 拦截器配置

    Spring interceptor拦截器配置 Spring mvc的拦截器是通过handlerinterceptor来实现的 实现方式: 1.自定义一个类实现Spring的handlerinterc ...

  6. Thinking in Java

    今天无意中看到了这本书(Thinking in Java)的中关于多态的一段描述,瞬间就感觉到了多态原来是这样的.

  7. leetcode@ [72/115] Edit Distance & Distinct Subsequences (Dynamic Programming)

    https://leetcode.com/problems/edit-distance/ Given two words word1 and word2, find the minimum numbe ...

  8. Java 8 开发顶级技巧

    本文由码农网 – 小峰原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划! 我使用Java 8编码已经有些年头,既用于新的应用程序,也用来迁移现有的应用,感觉是时候写一些我发现的非常有用的 ...

  9. Failed to install apk on device timeout

    安装应用时遇到下面的错误   Failed to install *.apk on device timeout 在eclipse中,window->prefreences->DDMS-& ...

  10. [OC Foundation框架 - 17] copy语法

    一个对象使用copy或mutableCopy方法可以创建对象的副本 1.copy 需要实现NSCopying协议 创建出来的是不可变副本,如NSString, NSArray, NSDictionar ...