为什么编译没有错误?(返回不对所述返回类型进行子类化的类型)

Why does this compile without errors? (Returning a type that doesn't subclass the stated returned type)

本文关键字:返回类型 子类 类型 有错误 编译 返回 为什么      更新时间:2023-10-16

我继承了std::list以允许使用[]运算符进行"伪随机访问"。

#include <list>
template <typename T>
class rlist : public std::list<T> {
    T& operator[](int index){
        typename std::list<T>::iterator iterator;
        int pos;
        for (iterator = this->begin(), pos = 0; iterator != this->end(); iterator++, pos++)
            if (pos == index)
                return *iterator;
        return inexistent_element();
    }
    class inexistent_element {
    };
};

inexistent_element还没有继承T,所以不应该编译。但它会编译。此外,我非常确信C++不应该允许我通过非常量引用传递内联创建的对象。

我正在使用Code::Blocks IDE和MinGW gcc编译器。我想知道为什么会编译。

您从未实例化过成员函数operator[]。我怎么知道的?这是私人的。

请注意,实例化类不会自动实例化其成员函数([temp.inst]/1):

类模板专门化的隐式实例化导致声明的隐式实例化,但不是类成员函数的定义或默认参数,成员类、作用域成员枚举、静态数据成员和成员模板;

显然,正如其他人所指出的,您从未实际实例化过operator[];编译器不需要诊断没有法律依据的情况实例化是可能的,不同的编译器也或多或少在这方面具有侵略性。(如果没有实例化;g++将诊断大多数没有法律依据的情况实例化。)

但当然,你的功能也可能有法律上的实例化。inexisting_element可能没有基类,但T可能有通过const引用获取inexisting_element的非显式构造函数,因此编译器在知道CCD_ 10之前不能合法地拒绝该代码;即函数已实例化。