为什么在某些情况下 cv 限定符会从函数 return 类型中删除?

Why do cv-qualifiers get removed from function return type in some cases?

看这个简单的例子:

template <typename T>
const T const_create() {
    return T();
}

struct Foo { };

int main() {
    auto &x = const_create<Foo>(); // compiles
    // auto &x = const_create<int>(); // doesn't compile
}

为什么带有 Foo 的版本可以编译,而带有 int 的版本却不能?换句话说,为什么 constconst_create<int> 的 return 类型中删除?它的工作方式与 returned int 而不是 const int 相同。这不是语言不通吗?

标准在哪里规定了这种行为?

[expr]/6 说:

If a prvalue initially has the type “cv T”, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.

因此,const Foo 右值只是 const Foo,但 const int 右值被调整为 int


此规则在 C++14 中引入(比较 N3337 [basic.lval]/4 with N4140 [expr]/6) by CWG 1261