问题
The following code compiles successfully both with clang++ 5.0.0 and g++ 7.2 (with the -std=c++17 -Wall -Wextra -Werror -pedantic-errors -O0
compilation flags):
struct Foo;
struct Bar
{
Foo get() const;
void set(Foo);
};
struct Foo
{
};
Foo Bar::get() const
{
return {};
}
void Bar::set(Foo)
{
}
int main()
{
Bar bar{};
(void)bar.get();
bar.set(Foo{});
}
Is it valid to use incomplete types as function parameters and return values? What does the C++ say on it?
回答1:
In a function definition, you cannot use incomplete types: [dcl.fct]/12:
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.
But a function declaration has no such restriction. By the time you define Bar::get
and Bar::set
, Foo
is a complete type, so the program is fine.
回答2:
Is it valid to use incomplete types as function parameters and return values? What does the C++ say on it?
In a function declaration, yes it is valid.
[basic.def.odr]
lists situations where a type must be complete. There is no mention of function declarations in that list. Note that function definitions do need the definition for T
for argument and return types of T
.
回答3:
As far as I know, you can use an incomplete type in the following ways:
- As pointers;
- As reference;
Because the declaration of the function doesn't create any object, so it is legal.
来源:https://stackoverflow.com/questions/47817012/incomplete-types-as-function-parameters-and-return-values