为什么编译器没有给出错误

Why is not the compiler giving error?

本文关键字:出错 错误 编译器 为什么      更新时间:2023-10-16

我在C++中使用以下示例程序

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
namespace mine{
    template<class T>
    inline void swap(T &a, T &b){
        char c= a; //This should not have compiled
        a=b;
        b=c;
    }
}
int main(){
    int a,b;
    cout<< "Enter two values: ";
    cin>>a>>b;
    mine::swap(a,b); //type variable T is instantiated as in
    cout << a <<' '<<b << endl;
}

我希望编译器在交换函数中抛出错误,因为 c 被声明为 char,但分配了一个泛型类型变量 T 的变量。不仅如此,在调用 swap 时,T 被实例化为 int。但是,g++不仅没有给出任何错误,而且程序运行良好。为什么会这样呢?

C++让你有能力搬起

石头砸自己的脚。

事实仍然是,任何整型类型都可以转换为具有实现定义行为的char

编译器假设你知道自己在做什么,仅此而已。

如今,auto c = a;将是最好的替代品。在 C++11 之前,你可以写T C = a;(当然你仍然可以。尽管从 C++11 开始,您应该在交换时使用std::move,但请查看如何在您的平台上实现std::swap。(参考标准库如何实现 std::swap?(

如果您在命令行上指定-Wconversion,GCC 将警告您这一点。

首先,将 int 转换为 char 是合法的,这是一个缩小的转换,如果您将其配置为这样做,编译器可能会警告您。

至于代码编译的原因,这是因为类型在编译时是已知的,因此编译器知道对于它初始化的所有 T 实例,T 可以转换为 char。

如果将 a 更改为不可转换为字符的类型,编译器将抱怨:例如使用 MSVC以下代码给出error C2440: 'initializing' : cannot convert from 'std::string' to 'char'

#include "stdafx.h"
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
namespace mine{
    template<class T>
    inline void swap(T &a, T &b){
        char c= a; //This should not have compiled
        a=b;
        b=c;
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    string a("test");
    string b("test2");
    mine::swap(a,b); //type variable T is instantiated as in
}
相关文章: