为什么编译器没有给出错误
Why is not the compiler giving error?
我在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
}
相关文章:
- 分段错误当我试图运行程序时出错
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 创建 OpenCV 非自由版本 v4.3 时出错,可折叠.cpp错误 C2039、2605
- 制作时出错,C++"db.c:2127:错误:在"||"标记之前应使用";"
- C++语法错误,编译器不会警告或 int v = func(&v) 出错;
- 在VS2015中访问类成员时运行时错误,但在Linux上未访问时出错
- 如何更改路径以修复错误"./main:加载共享库 libmkl_core.so 时出错?
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- 安装 mply 库时出错.致命错误:gsl/gsl_sf.h:没有这样的文件或目录
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- 编译特征程序时出错:错误:'seq'不是'Eigen'的成员
- 可能的 GCC 链接器错误会导致将弱符号和局部符号链接在一起时出错
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 运算符重载时出错(错误:"运算符<<不匹配(操作数类型为"std::basic_ostream<char>"和"const char [2]")
- 编译类 C++ 中的线程时出错(错误 xthread)
- 加载GLEW库时出错(错误LNK2001)
- 通过函数指针调用函数时出错(错误C2064)
- 编译core.obj时出错:错误LNK2001:未解析的外部符号_harmony_core_init
- 链接c++静态库与android ndk时出错(错误:无法识别文件格式)
- 使用GCC编译游戏时出错.(错误:将"Screen"的含义从"class Screen&q