是否需要定义我的退货类型? [英] Does my Return Type Need to be Defined?
问题描述
转发声明让我们推迟定义实际类型,直到实施文件.标头中允许使用指针或引用来声明前向声明的类型.
Forward declaration lets us postpone defining an actual type till the implementation file. This is allowed in the header for pointers or references to a forward declared type.
有人告诉我该:
按值返回不需要类型定义.向前声明就足够
Returning by value does not require the type definition. A forward declaration is sufficient
有人可以使用标准中的实际报价来确认或否认吗?我觉得这是不合法的.
Can someone confirm or deny this with an actual quote from the standard? I was under the impression that this was not legal.
推荐答案
按值返回不需要类型定义.向前声明就足够
Returning by value does not require the type definition. A forward declaration is sufficient
声明按值返回的函数不需要类型定义.格式正确的演示:
Declaring a function that returns by value does not require the type definition. A well-formed demo:
struct S;
S foo();
struct S {};
int main() {
foo();
}
S foo() {
return {};
}
定义或调用按值返回的函数确实需要类型定义.标准草案 [basic.def.odr] :
Defining or calling a function that returns by value does require the type definition. Standard draft [basic.def.odr]:
5如果以某种要求完整的类类型的方式使用该类,则在翻译单元中确实需要一个类的定义. [示例:... [snip] ... [注意:声明和表达式规则描述了在哪些上下文中需要完整的类类型. 如果满足以下条件,则类型T必须为完整:
- [snip]
- 5.9定义([basic.def])或调用([expr.call])或返回类型为T的函数,或者
- [snip]
- [snip]
- 5.9 a function with a return type or argument type of type T is defined ([basic.def]) or called ([expr.call]), or
- [snip]
由于不被列表中的任何规则所禁止,因此隐式地允许声明具有不完整返回类型的函数.
The declaration of a function with incomplete return type is implicitly allowed by virtue of not being forbidden by any of the rules in the list.
The rule is re-worded later in the standard, and it is relaxed by an exception [dcl.fct] (thanks to @cpplearner for pointing this rule out):
11不得在返回或参数类型中定义类型.在函数定义的上下文中,参数的类型或函数定义的返回类型不应是不完整的(可能是cv限定的)类类型,除非删除了该函数([dcl.fct.def.delete]).
11 Types shall not be defined in return or parameter types. The type of a parameter or the return type for a function definition shall not be an incomplete (possibly cv-qualified) class type in the context of the function definition unless the function is deleted ([dcl.fct.def.delete]).
格式不正确的演示
An ill-formed demo:
struct S;
S foo() {
return {};
} // oops
struct S {};
另一个格式不正确的演示
Another ill-formed demo:
struct S;
S foo();
int main() {
foo(); // oops
}
struct S {};
S foo() {
return {};
}
这篇关于是否需要定义我的退货类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!