C++: Using '.' operator on expressions and

2019-07-08 07:50发布

I was wondering if it is good practice to use the member operator . like this:

someVector = (segment.getFirst() - segment.getSecond()).normalize().normalCCW();

Just made that to show the two different things I was wondering, namely if using (expressions).member/function() and foo.getBar().getmoreBar() were in keeping with the spirit of readability and maintainability. In all the c++ code and books I learned from, I've never seen it used in this way, yet its intoxicatingly easy to use it as such. Don't want to develop any bad habits though.

Probably more (or less) important than that, I was also wondering if there would be any performance gains/losses by using it in this fashion, or unforeseen pitfalls that would introduce bugs into the program.

Thank you in advance!

8条回答
唯我独甜
2楼-- · 2019-07-08 08:16

Yes, this is perfectly acceptable and in fact would be completely unreadable in a lot of contexts if you were to NOT do this.

It's called method chaining.

There MIGHT be some performance gain in that you're not creating temporary variables. But any competent compiler will optimise it anyway.

查看更多
闹够了就滚
3楼-- · 2019-07-08 08:18

Using a variable to hold intermediate results can sometimes enhance readability, especially if you use good variable names. Excessive chaining can make it hard to understand what is happening. You have to use your judgement to decide if it's worthwhile to break down chains using variables. The example you present above is not excessive to me. Performance shouldn't differ much one way or the other if you enable optimization.

查看更多
相关推荐>>
4楼-- · 2019-07-08 08:22

There's no big problem with using it in this way- some APIs benefit greatly from method chaining. Plus, it's misleading to create a variable, and then only use it once. When someone reads the next line, they don't have to think about all those variables that you now didn't keep.

查看更多
爷、活的狠高调
5楼-- · 2019-07-08 08:31

It depends of what you're doing.

For readability you should try to use intermediate variables.
Assign calculation results to pointers, and then use them.

查看更多
一纸荒年 Trace。
6楼-- · 2019-07-08 08:37
someVector = (segment.getFirst() - segment.getSecond()).normalize().normalCCW();

Not an answer to your question, but I should tell you that the behavior of the expression (segment.getFirst() - segment.getSecond()) is not well-defined as per the C++ Standard. The order in which each operand is evaluated is unspecified by the Standard!

Also, see this related topic : Is this code well-defined?

查看更多
We Are One
7楼-- · 2019-07-08 08:38

I suppose what you are doing is less readable, however on the other hand, too many temporary variables can also become unreadable.

As far performance I'm sure there is a little overhead when making temporary variables but the compiler could optimize that out.

查看更多
登录 后发表回答