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


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

    /*
     * 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
    ", (a+1), a);
    	else
    		printf("%d <= %d
    ", (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
    ", 1 << 33);
    	printf("%d
    ", 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 是不一样的

  • 相关阅读:
    PHP调试总结
    vim常用命令
    Xshell
    JavaScript
    HTML+CSS
    解决VMware“该虚拟机似乎正在使用中”问题
    MVC dirname(——FILE——)
    各种编程语言中的指针和引用
    Go defer 原理和源码剖析
    软件架构定义的流派
  • 原文地址:https://www.cnblogs.com/shhu1993/p/5244315.html
Copyright © 2020-2023  润新知