开发者

obj1 *= obj2 VS. obj1 = obj1 * obj2 in C++

Assuming that i've implemented *=, = and * operators overloading, which will you prefer to use complexity wise? Thank开发者_开发百科s.


Given that I’d usually implement operator * in terms of operator *= and a copy, there is no reason ever to prefer operator *.

The normal implementation of operator * (and +, -, / etc.) should usually look as follows:

T operator *(T const& left, T const& right) {
    T result = left;
    return result *= right;
}


Both usages are NOT complex for simple operations like the one you have specified. But, for longer expressions, *= can make things more readable.


If you've implemented them normally, then prefer *=. The other way will require making a copy, then applying *= to it, then assigning it back.


The = and * separate implementations are more useful. It allows a * b * c * d type expressions. However consider the overhead of additional copies being created, as noted by Benjamin Lindley.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜