开发者

What could go wrong if you don't pass objects by reference into a function

I am trying to teach some students that in the following case you should pass by reference, otherwise the objects will be copied.

note: Th开发者_运维知识库ey don't know about copy-constructors yet, so if possible I would not like to mention them in the example.

int sumOfSizes(CObject const & a, CObject const & b)
{
    return a.getSize() + b.getSize();
}

Can anybody help me with a real-world example where the sum is infact not what is expected?


As @Space_C0wb0y implied in his comment, the only way this could do something "unexpected" when passing by value is if the copy constructor for CObject did something "unexpected" (such that the local CObject instances were not equivalent (in whatever sense) to the original instances). This in turn would indicate bad design.

Therefore, your counterexample will have to rely on a contrived, badly-designed CObject.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜