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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With