【发布时间】:2016-07-22 19:08:35
【问题描述】:
此代码在 g++ 6.1 下编译成功,但使用 clang 3.8 时出错:
class C;
class Base {
public:
virtual const C *getC();
};
class Derived : public Base {
public:
virtual C *getC();
};
clang报错如下:
$ dev/compilers/linux-x86_64-2.12.2/clang3.8/bin/clang++ -Wall -c testcovariantreturn.cxx
testcovariantreturn.cxx:10:20: error: return type of virtual function 'getC' is not covariant with the return type of the function it overrides ('C' is incomplete)
如果类 C 是完全定义的而不是前向声明的,则没有错误。我的理解是,在覆盖虚拟方法时,协变允许“较小”的 cv 限定(即,从返回类型中删除 const)。
clang 是否正确/允许需要完整的类型,如果是,为什么?有 C 的定义可用如何改变这里的任何东西?
这并不完全是学术性的,在大型代码库中我不愿意添加不必要的包含,我们尝试将声明作为标准做法。
【问题讨论】:
-
此代码是协变的,因此理想情况下它应该被接受。相反的
const方差不会是协变的,并且会支持原始const对象的UB 修改。这就是说(这很重要)我不知道 C++ 标准对此有什么看法,如果有的话。
标签: c++ covariance