简体   繁体   English

我可以在覆盖虚函数的返回类型中丢失“constness”吗?

[英]Can I lose “constness” in the return type of an override virtual function?

The following code compiles and runs, and no warning is emitted by either gcc or clang: 以下代码编译并运行,并且gcc或clang不会发出警告:

#include <iostream>

struct Base {
    virtual ~Base() = default;
    virtual std::string const& get() = 0;
};

struct Derived: Base {
    virtual std::string& get() override { return m; }
    std::string m;
};

int main()
{
    Derived d;
    d.get() = "Hello, World";

    Base& b = d;
    std::cout << b.get() << "\n";
}

Is std::string& covariant with std::string const& then? std::string& covariant与std::string const&然后呢?

Yes

This is specified in class.virtual , in the latest draft (n4606) we see: 这是在class.virtual中指定的,在我们看到的最新草案(n4606)中:

§10.3 7/ The return type of an overriding function shall be either identical to the return type of the overridden function or covariant with the classes of the functions. §10.37 /重写函数的返回类型应与被覆函数的返回类型相同,或者与函数类的协变相同。 If a function D::f overrides a function B::f , the return types of the functions are covariant if they satisfy the following criteria: 如果函数D::f覆盖函数B::f ,则函数的返回类型如果满足以下条件则是协变的:

  • both are pointers to classes, both are lvalue references to classes, or both are rvalue references to classes 111 两者都是类的指针,都是对类的左值引用,或者两者都是对类111的右值引用
  • the class in the return type of B::f is the same class as the class in the return type of D::f , or is an unambiguous and accessible direct or indirect base class of the class in the return type of D::f 在返回类型的类B::f是相同的类中的返回类型的类D::f ,或者是一个明确的和可访问的直接或间接的基类中的返回类型的类的D::f
  • both pointers or references have the same cv-qualification and the class type in the return type of D::f has the same cv-qualification as or less cv-qualification than the class type in the return type of B::f . 指针或引用具有相同的cv限定,并且返回类型D::f中的类类型具有与B::f的返回类型中的类类型相同的cv-qualification或更少的cv-qualification。

Specifically, the last point addresses exactly the case here: it is acceptable for an overriding type to lose the const and/or volatile qualifiers (it cannot, however, gain them). 具体来说,最后一点完全解决了这里的情况:重写类型可以接受丢失const和/或volatile限定符(但不能获得它们)。


Note: as mentioned by @george above, paragraph 8/ used to prevent this from working with incomplete class types, but this was since fixed . 注意:正如@george上面提到的,第8段/用于防止这种情况与不完整的类类型一起使用,但这是固定的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM