Why this warning from IBM XL C/C++ compiler?

后端 未结 4 1324
感情败类
感情败类 2021-01-12 07:38

Here\'s a minimum code example that illustrates the problem:

#include 

class Thing
{
   // Non-copyable
   Thing(const Thing&);
   Thing         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-01-12 07:58

    The rules for this are in §8.5.3/5 of the standard. There are three basic situations identified. The first involve the initializer ('3' in your case) being either an lvalue, or having class type. Since neither of those is true, what you have is the third case: initializing a const reference with an rvalue that does not have a class type. This case is covered by the final bullet in 8.5.3/5:

    Otherwise, a temporary of type “cv1 T1” is created and initialized from the initializer expression using the rules for a non-reference copy initialization (8.5). The reference is then bound to the temporary. If T1 is reference-related to T2, cv1 must be the same cv-qualification as, or greater cv-qualification than, cv2; otherwise, the program is ill-formed.

    Edit: rereading, I think IBM has it right. I was previously thinking of the possibility of having to copy the temporary, but that's not the source of the problem. To create the temporary using non-reference copy initialization as specified in §8.5, it needs the copy ctor. In particular, at this point it's equivalent to an expression like:

    T x = a;

    This is basically equivalent to:

    T x = T(a);

    I.e. it's required to create a temporary, then copy the temporary to the object being initialized (which, in this case, is also a temporary). To summarize the required process, it's roughly equivalent to code like:

    T temp1(3);
    T temp2(temp1); // requires copy ctor
    show(temp2);    // show's reference parameter binds directly to temp2
    

提交回复
热议问题