一些有意思,有深度,容易错的代码收集
2016-03-05 10:50
351 查看
Link
一些有意思,有容易错误的代码,下面列了几个,其他的参见上述的网址
/* * main.cpp * * Created on: Mar 5, 2016 * Author: xiaophuang */ #include <vector> #include <iostream> using namespace std; /* This one may well work with some compilers/OS, and crash with others. Who said the STL was safe ?? */ int main() { vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); for (vector<int>::iterator i = v.begin();i != v.end(); i++) { cout << *i << endl; if (*i == 1) { v.push_back(5); } } }
如果不动态的删减vector的元素,就没有异常,还没有想清楚, 为什么Todo
#include <stdio.h> #include <limits.h> void compare (int a) { if ((a+1) > a) printf("%d > %d\n", (a+1), a); else printf("%d <= %d\n", (a+1), a); } int main () { /* * When compiled with gcc -O0, I get different results for * both lines. With gcc -O1, I get the same. When compiling * with clang, I even more surprising results. * * Surprisingly (or not), these results do not correspond to * bugs in the compilers. * * The warning given by both compilers helps understanding * what's going on, but I had to read the standard to really * get it. */ int i = 33; printf("%d\n", 1 << 33); printf("%d\n", 1 << i); /* * adapted from http://blog.regehr.org/archives/213 * * Try compiling this with -O0 and with -O3, and see ... * Again, no compiler bug involved! */ compare(1); compare(INT_MAX); }
不同的编译器选项不同的效果
#include <iostream> using namespace std; struct B { virtual void whoami () const {cout << "B" << endl;} }; struct D : public B { void whoami () {cout << "D" << endl;} }; int main() { D d; B *b = &d; b->whoami(); // B D *dd = &d; dd->whoami(); //D }
const 加入的效果和没有const 是不一样的
相关文章推荐
- VBS 从指定 DNS 获取给定域名(Domain)的 IP 地址
- 基于python快速实现排列组合算法
- Zend Framework动作助手Json用法实例分析
- 关于yii2里面的\yii\helpers\Url组件
- Python 基础语法(四)
- 快速排序的一个Java实现
- TP 模板中截取字符串
- IT十八掌作业_java基础第三天_数组
- Python 基础语法(三)
- php中mysqli_errno和mysqli_error的区别
- QT信号和槽用于对象之间的通信
- 跟着开涛学SpringMVC
- Python 基础语法(二)
- thinking in java 21_03
- Python 基础语法(一)
- java web中如何处理表单中的中文
- Spring Data JPA教程:审计(二)
- java 安装及配置
- python中的cm()len() list() and tuple()以及一些内建函数
- leetcode:Reverse Integer 【Java】