Why is my return type meaningless?

后端 未结 6 740
别跟我提以往
别跟我提以往 2021-01-11 16:05

I am trying to use a return type of const MyClass * const. However, I get a warning:

Warning: #815-D: type qualifier on return type is m

6条回答
  •  不要未来只要你来
    2021-01-11 16:49

    Why return a const value? Consider the following (and please excuse the unimaginative variable names):

    struct A { int a; };
    
    A operator+(const A& a1, const A& a2) 
    {
        A a3 = { a1.a + a2.a };
        return a3;
    }
    

    Given that declaration of operator+, I can do the following:

    A a = {2}, b = {3}, c = {4}, d = ((a+b) = c);
    

    That's right, I just assigned to the temporary A that was returned by operator+. The resulting value of d.a is 4, not 5. Changing the return type of operator+ to const A prevents this assignment, causing the expression (a+b) = c to generate a compiler error.

    If I try to assign to a pointer or integer returned from a function, my compiler (MSVC) generates a "left operand must be l-value" error, which seems consistent with the ARM compiler telling you that the constness of the pointer is meaningless--the pointer can't be assigned to anyway. But for classes/structs, apparently it's okay to assign to non-const return values.

提交回复
热议问题