一些有意思,有深度,容易错的代码收集

一些有意思,有容易错误的代码,下面列了几个,其他的参见上述的网址

/*
 * 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 是不一样的

posted @ 2016-03-05 10:50  逍遥客33  阅读(215)  评论(0编辑  收藏  举报