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

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

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

转载于:https://www.cnblogs.com/shhu1993/p/5244315.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值