Chinaunix

标题: More Effective C++ 之 条款 20 ,在阅读 的 时候不是很 明白! [打印本页]

作者: haochao    时间: 2009-03-28 05:54
标题: More Effective C++ 之 条款 20 ,在阅读 的 时候不是很 明白!
其中在讲到通过调用Rational类的构造 函数来降低临时对象的开销 :





// an efficient and  correct way to implement
// a function that returns an object

const Rational operstor*(const Rational& lhs,const Rational& rhs)
{
        return Rational(lhs.numberator()* rhs.numerator(),
                                      lhs.denominator() * rhs.denominator());
}

我 不 明白 的就是在这里,调用Rational类的构造函数(而且还没有该对象名字),这里是什么语义,那么C++好手
能否说一下在 "ANSI c++ Standard"上那一节能找到这个知识点!谢谢了!
作者: ruanunix    时间: 2009-03-28 12:06
Rational(lhs.numberator()* rhs.numerator(),
                                      lhs.denominator() * rhs.denominator());

这个就是构造函数啊,只是使用的是显性调用,Rational(int, int);
一个类可以有很多构造函数,但是有一个缺省的,可以隐性调用,也可以显性调用
作者: emacsnw    时间: 2009-03-28 13:29
原帖由 haochao 于 2009-3-27 13:54 发表
其中在讲到通过调用Rational类的构造 函数来降低临时对象的开销 :





// an efficient and  correct way to implement
// a function that returns an object

const Rational operstor*(const Rat ...


构造一个临时对象,返回的是对象的拷贝而不是引用(或者指针),因此是安全的。
作者: haochao    时间: 2009-03-28 15:48
呵呵,这个 条款的重点并不是“安全不安全”, 通过避免局部对象对象的创建使其更有效率
作者: huachong    时间: 2009-03-28 15:58
如果创建了局部对象,就多了一次拷贝操作
Rationa A = Rational(lhs.numberator()* rhs.numerator(),
                                      lhs.denominator() * rhs.denominator());
return A;
首先创建A,调用ct,然后返回一个A的拷贝,然后调用A的dt
你不觉得多做了一些操作吗?
作者: emacsnw    时间: 2009-03-28 16:38
原帖由 haochao 于 2009-3-27 23:48 发表
呵呵,这个 条款的重点并不是“安全不安全”, 通过避免局部对象对象的创建使其更有效率


你看了这个条款没有?你举的代码的上一段代码就是同样的函数,只不过返回的是const Rational&
上面有段注释:
// another dangerous (and incorrect) way to avoid
// returning an object

你问的问题很简单,语法上就是构造了一个临时对象,并且返回。
重点是为什么这样是安全的。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2