Are temporary objects in C++ const indeed?

前端 未结 6 1595
走了就别回头了
走了就别回头了 2021-01-06 10:11

I always believed that temporary objects in C++ are automatically considered as const by the compiler. But recently I experienced that the following example of code:

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 11:02

    It depends.

    int f();
    const int g();
    
    class C { };
    C x();
    const C y();
    

    In the case of both f() and g(), the returned value is not const because there are no const-qualified rvalues of non-class type. The const in the return type of g() is completely useless (in fact, it's worse than useless, since it can in rare circumstances cause issues with template instantiation).

    In the case of x(), the returned value is not const (because it isn't const-qualified). In the case of y(), the returned value is const (because the return type is const-qualified). The const qualifier here (or lack thereof) is meaningful because the return type is a class type.

提交回复
热议问题