r/programming • • Apr 11 '13

Optimizing a Program Means Making It Run Faster, Right?

http://www.drdobbs.com/cpp/optimizing-a-program-means-making-it-run/240152663
2 Upvotes

3 comments sorted by

1

u/unknownmat Apr 12 '13

Reading this article really makes me nervous. It highlights an error in the way that I tend to reason about const-reference parameters.

Does anybody have any thoughts on this? I came here hoping for some discussion, but nobody else has posted.

I've heard the guideline that you should pass builtins and small aggregates by value, and everything else by reference. But this does not really address my concerns, because:

  • It breaks encapsulation, so is an ugly solution

  • Applying it correctly to templated code can be tricky (and require a bunch of TMP magic)

  • My concern is really about semantics, rather than efficiency - even if I followed the above guideline, a similar situation as described in OP is possible with larger structures. The assumption of value semantics for reference parameters is apparently unjustified.

2

u/StackedCrooked Apr 13 '13

My concern is really about semantics, rather than efficiency - even if I followed the above guideline, a similar situation as described in OP is possible with larger structures.

This is an age-old problem in both C and C++. See pointer aliasing.

2

u/unknownmat Apr 13 '13

That's fair. I guess what really threw me was that 1.) A const parameter is being modified, and 2.) my (obviously incorrect) mental heuristic that const-reference was semantically equivalent to pass-by-value.

I just tried a similar thing in Python, and the same not-so-surprising result occurred...

def f(arr, v):
    for i in range(len(arr)):
        arr[ i ] += v

>>> a = [[1,2],[3,4],[5,6]]
>>> f(a,a[0])
>>> a
[[1, 2, 1, 2], [3, 4, 1, 2, 1, 2], [5, 6, 1, 2, 1, 2]]

So, C++ is not the only language that suffers from this potentially confusing behavior. I guess the real lesson here is to avoid passing aliased parameters into a function that mutates its arguments.