Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incomplete types as function parameters and return values

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?

like image 594
Constructor Avatar asked Dec 14 '17 15:12

Constructor


2 Answers

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.

like image 150
Barry Avatar answered Nov 03 '22 00:11

Barry


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.

like image 38
eerorika Avatar answered Nov 03 '22 00:11

eerorika