C++ execution order in method chaining

前端 未结 4 448
猫巷女王i
猫巷女王i 2021-01-30 12:32

The output of this program:

#include  
class c1
{   
  public:
    c1& meth1(int* ar) {
      std::cout << \"method 1\" << std::e         


        
4条回答
  •  温柔的废话
    2021-01-30 12:56

    In the 1998 C++ standard, Section 5, para 4

    Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

    (I've omitted a reference to footnote #53 which is not relevant to this question).

    Essentially, &nu must be evaluated before calling c1::meth1(), and nu must be evaluated before calling c1::meth2(). There is, however, no requirement that nu be evaluated before &nu (e.g. it is permitted that nu be evaluated first, then &nu, and then c1::meth1() is called - which might be what your compiler is doing). The expression *ar = 1 in c1::meth1() is therefore not guaranteed to be evaluated before nu in main() is evaluated, in order to be passed to c1::meth2().

    Later C++ standards (which I don't currently have on the PC I'm using tonight) have essentially the same clause.

提交回复
热议问题