Incomplete types as function parameters and return values

北战南征 提交于 2020-04-09 15:49:12

问题


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:

  1. As pointers;
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!