[翻译] Effective C++, 3rd Edition, Item 21: 当你必须返回一个 object(对象)时不要试图返回一个 reference(引用)(下)

(点击此处,接上篇)

但是也许你注意到无论是 on-the-stack(在栈上)的还是 on-the-heap(在堆上)的方法,为了从 operator* 返回的每一个结果都不得不容忍一次 constructor(构造函数)的调用。也许你还记得我们最初的目标是避免这样的 constructor(构造函数)调用。也许你认为你知道一种方法能避免除一次以外的几乎全部的 constructor(构造函数)调用。也许下面这个实现是你做过的,一个基于返回一个引向定义在函数内部的 static Rational object 的 references(引用)的 operator* 的实现:

const Rational& operator*(const Rational& lhs,    // warning! yet more
                          const Rational& rhs)    // bad code!
{
  static Rational result;             // static object to which a
                                      // reference will be returned

  result = ... ;                      // multiply lhs by rhs and put the
                                      // product inside result
  return result;
}

就像所有使用了 static object 的设计一样,这个也会立即引起我们的 thread-safety(线程安全)的混乱,但那是它的比较明显的弱点。为了看到它的更深层的缺陷,考虑这个完全合理的客户代码:

bool operator==(const Rational& lhs,            // an operator==
                const Rational& rhs);           // for Rationals

Rational a, b, c, d;

...
if ((a * b) == (c * d))  {
    do whatever's appropriate when the products are equal;
} else    {
    do whatever's appropriate when they're not;
}

猜猜会怎么样?不管 abcd 的值是什么,表达式 ((a*b) == (c*d)) 总是等于 true

将代码重写为功能完全等价的另一种形式时,这一发现就很容易被理解了:

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

注意,当 operator== 被调用时,将同时存在两个起作用的对 operator* 的调用,每一个都将返回引向 operator* 内部的 static Rational object 的引用。因此,operator== 将被要求比较 operator* 内部的 static Rational object 的值和 operator* 内部的 static Rational object 的值。如果它们不是永远相等,那才真的会令人大惊失色了。

这些应该足够让你确信试图从类似 operator* 这样的函数中返回一个引用纯粹是浪费时间,但是你们中的某些人现在会这样想“好吧,就算一个 static 不够用,也许一个 static array(数组)是一个窍门……”

我无法拿出示例代码来肯定这个设计,但我可以概要说明为什么这个想法应该让你羞愧得无地自容。首先,你必须选择一个 n 作为数组的大小。如果 n 太小,你可能会用完存储函数返回值的空间,与刚刚名誉扫地的 single-static 设计相比,在任何一个方面你都不会得到更多的东西。但是如果 n 太大,就会降低你的程序的性能,因为在函数第一次被调用的时候数组中的 every object(每一个对象)都会被构造。即使这个我们正在讨论的函数仅被调用了一次,也将让你付出 n 个 constructors(构造函数)和 n 个 destructors(析构函数)的成本。如果 "optimization"(“优化”)是提高软件性能的过程,这种东西也只能被称为 "pessimization"(“悲观主义”)的。最后,考虑你怎样将你所需要的值放入数组的 objects 中,以及你做这些需要付出什么。在两个 objects 间移动一个值的最直接方法就是通过 assignment(赋值),但是一次 assignment(赋值)将要付出什么?对于很多类型,这就大约相当于调用一次 destructor(析构函数)(销毁原来的值)加上调用一次 constructor(构造函数)(把新值拷贝过去)。但是你的目标是避免付出 construction(构造)和 destruction(析构)成本!面对的结果就是:这个方法绝对不会成功。(不,用一个 vector 代替一个 array(数组)也不会让事情有多少改进。)

写一个必须返回一个 new object(新对象)的函数的正确方法就是让那个函数返回一个 new object(新对象)。对于 Rationaloperator*,这就意味着下面这些代码或在本质上与其相当的某些东西:

inline const Rational operator*(const Rational& lhs, const Rational& rhs)
{
  return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}

当然,你可能付出了构造和析构 operator* 的返回值的成本,但是从长远看,这只是为正确行为付出的很小的代价。除此之外,那种令你感到恐怖的账单也许永远都不会到达。就像所有的程序设计语言,C++ 允许编译器的实现者在不改变生成代码的可观察行为的条件下使用优化来提升它的性能,在某些条件下会产生如下结果:operator* 的返回值的 construction(构造)和 destruction(析构)可以被安全地消除。当编译器利用了这一点时(编译器经常这样做),你的程序行为还是符合你的期待,只是比你期待的更快。

全部的焦点在这里:如果需要在返回一个 reference(引用)和返回一个 object(对象)之间做出决定,你的工作就是让选择能提供正确的行为的那一个。让你的编译器厂商去绞尽脑汁使那个选择尽可能地廉价。

Things to Remember

  • 绝不要返回一个 local stack object(局部栈对象)的指针或引用,绝不要返回一个 heap-allocated object(被分配堆对象)的引用,或者如果存在需要一个以上这样的 object 的可能性时,绝不要返回一个 local static object(局部静态对象)的指针或引用。(Item 4 提供的一个返回一个引向 local static(局部静态)的引用的设计的例子至少在 single-threaded environments(单线程的环境)中是合理的。)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Alex Allain(Cprogramming.com)的推荐 If you want to really and truly understand C++, you must read Effective C++. After first reading Effective C++, I had a totally new appreciation for and understanding of C++. And it's not just me: this book gets 5 stars on Amazon (with over 140 reviews!). One of the reviewers even titles his review: "Don't write C++ code without it..." And I agree. I wouldn't hire someone to work for me that doesn't know the information in this book (or have plans to learn it soon). When we hire interns at my company, this is the book we give them to read. So what exactly will you learn? Scott Meyers does a great job of figuring out what little details are important, distilling the vast sea of knowledge about C++ into the 55 specific tips that are most useful for practicing C++ programmers. This isn't just a "what to do" book--it's a "why" book; every tip explains the reason for it, so you'll understand it and remember it better. In fact, even though the book is split across 55 tips, it feels like a holistic description of how to effectively use C++. Some of the specific things you'll learn: what functions are always part of a class and why it matters to you what to watch out for when writing an assignment operator How to avoid common pitfalls when creating class hierarchies how to write code designed for others to use simple techniques that can lead to huge performance improvements advanced C++ techniques, including use of the STL (with lots of examples) And much much more... If you are serious about becoming a C++ expert, buy ONE book on C++, this would be the book. (Yes, even over Bjarne Stroustrup's "The C++ Programming Language"--it's that good.) So buy Effective C++ today and write better programs tomorrow! Alex 49 Dover St. #37, Somerville, MA 02144, USA

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值