Why are by-value parameters excluded from NRVO?

后端 未结 6 1680
孤独总比滥情好
孤独总比滥情好 2020-11-27 18:12

Imagine:

S f(S a) {
  return a;
}

Why is it not allowed to alias a and the return value slot?

S s = f(t);
S s          


        
6条回答
  •  独厮守ぢ
    2020-11-27 18:58

    I think the issue is that if the copy constructor does something, then the compiler must do that thing a predictable number of times. If you have a class that increments a counter every time it's copied, for example, and there's a way to access that counter, then a standards-compliant compiler must do that operation a well-defined number of times (otherwise, how would one write unit tests?)

    Now, it's probably a bad idea to actually write a class like that, but it's not the compiler's job to figure that out, only to make sure that the output is correct and consistent.

提交回复
热议问题