c++ - 作为函数参数和返回值的不完整类型

标签 c++ language-lawyer c++17 return-type incomplete-type

以下代码compiles successfully both with clang++ 5.0.0 and g++ 7.2 (使用 -std=c++17 -Wall -Wextra -Werror -pedantic-errors -O0 编译标志):

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{});
}

使用不完整类型作为函数参数和返回值是否有效? C++ 在上面说了什么?

最佳答案

在函数定义中,您不能使用不完整的类型:[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.

但是函数声明 没有这样的限制。当你定义 Bar::getBar::set 时,Foo 是一个完整的类型,所以程序没问题。

关于c++ - 作为函数参数和返回值的不完整类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47817012/

相关文章:

c++ - std::for_each 和仿函数 - operator() 可以有哪些签名?

c++ - 为什么 Utf-8 在 Qt 5 中无法工作?

c++ - 标准是否认为模板类的非模板成员本身是 "templates"?

c++ - 您可以将一个 union 成员的值(value)分配给另一个 union 成员吗?

c++ - 返回本地对象的元组

c++ - 使用包扩展的 Lambda 继承

c++ - 如果指针的大小都相同,为什么我们必须声明它们指向的对象类型?

c++ - 在 C++ 中将字符串 "\u0026"转换为 "&"

c++ - 通过 unsigned char[] 创建隐式对象 - reinterpret_cast 为隐式对象是否合法? (P0593)

c++ - constexpr if with initializer 由标准保证吗? 'constexpr(constexpr auto x = f(); x) { }'