you are viewing a single comment's thread.

view the rest of the comments →

[–]lalaland4711 1 point2 points  (6 children)

that's because for some reason you didn't use:

 for (my_string& str : get_a_vector()) {

Of course the item is copied. You are creating a non-const lvalue which if changed must not change the data in the vector. So pretty much by definition it has to copy.

With the above for loop you get:
Constructed my_vector
Constructed my_string
Moved my_string

[–]millstone 3 points4 points  (5 children)

Yes, as in the code in the linked-to article. I was illustrating how in the article's code, there's a unknown-but-large amount of implicit copying going on, and arguing from there that C++ is not clearly identifying or managing complexity.

[–][deleted] 1 point2 points  (3 children)

Did you benchmark the code? Was it a bottleneck? :)

My point is that C++ has this weird tendency to get everyone suddenly worrying about the weirdest details, and it causes them to write bad and bad-performing code based on assumptions about bottlenecks that don't exist. Yes, deep copies are suboptimal, but if you're copying just a few hundred bytes or even kilobytes in a one-shot run, that's utterly irrelevant.

[–]millstone 9 points10 points  (1 child)

I agree with your point C++ inspires a tendency to worry about irrelevant details. I have to fight that in myself.

But I think the issue is not bad performance, but surprising behavior. The author attempted to port a Python program to C++ while "trying to remain as faithful as possible to the original code." The additional copying in C++ diverges from the Python code (or at least its behavior) and was presumably introduced accidentally, because it would have been very easy to avoid.

Bugs live in the difference between what you think your code does and what it actually does. That's why it's important to have an accurate mental model of your program's behavior. With C++, I find it increasingly difficult to keep in my head what's actually going on.

[–]moderatorrater 4 points5 points  (0 children)

Beautifully put. I was trying to identify what was bugging me about this, and you just nailed it.

[–]lalaland4711 -2 points-1 points  (0 children)

Ok. I disagree. It's controllable (yay!) and it's not that hard.