编译器未为类的构造函数抛出错误有语法错误

Compiler not throwing error for constructor of class has syntax error

本文关键字:错误 出错 语法 构造函数 编译器      更新时间:2023-10-16

我有以下一段代码,我真的犯了一个语法错误:

#include<iostream>
using namespace std;
template<typename Type1,typename Type2>
class Pair{
public:
    Type1 first;
    Type2 second;
    Pair();
    Pair(Pair<Type1,Type2>& obj);
};
template<class Type1,class Type2>
Pair<Type1,Type2>::Pair(){
    first=Type1();
    second=Type2();
}
template<class Type1,class Type2>
Pair<Type1,Type2>::Pair(Pair<Type1,Type2>& obj1){
        cout<<"Inside the copy constructorn";
        obj1.first=                                //THIS IS THE PROBLEMATIC STMNT
}
int main()
{
/* Code here */
Pair<int,int> com1;
//Pair<complex1,complex2> com2(com1);
}

我在这个程序中没有发现任何编译/运行时错误。但是,如果我取消main中调用复制构造函数的第二行注释,则会抛出编译器时间错误。我知道类在运行时是根据类型进行初始化的,但是像这样的语法错误肯定会在编译阶段在模板化的类中进行检查。为什么没有编译时错误?

Pair<complex1,complex2> com1;使用默认构造函数,而Pair<complex1,complex2> com2(com1);使用复制构造函数。

由于没有第二行,永远不会使用复制构造函数,因此不会编译;编译器从不为它生成代码,因此它从不检查它是否可以编译。

这是一个编译器错误。您可以用一种更简单的方式复制它:

template <class T>
void f()
{
   = // should be an error, but is not in MSVC
}
int main()
{
}

这将在非MSVC编译器中创建一个类似error: expected primary-expression before '=' token的诊断消息,但在MSVC中可以正常编译。

明显的原因是MSVC仍然没有实现c++标准所要求的两阶段查找。正如MSVC开发人员Stephan T. Lavavej最近在Visual c++团队博客中解释的那样:

VC还没有实现c++ 98/03的三个特性:两阶段名称查找,动态异常规范,并导出。两阶段名称查找在2015年仍未实现,但它在编译器团队的列表中要做的事情,等待代码库现代化

相关文章: