1 调用strtok,会修改你输入的参数。
我刚刚犯了一个错误,就是先调用了strtok,然后才检查字符串,结果没有按预期。
// 错误
char buf[256] = "0,100";
char* res = strtok( buf, ",;" );
if( buf[0] == '0' && buf[1] == '\0' ) return -1;
// 正确
char buf[256] = "0,100";
if( buf[0] == '0' && buf[1] == '\0' ) return -1;
char* res = strtok( buf, ",;" );
2 调用一些win api的时候,#include <winbase.h>会提示很多未定义的错误,应该改为#include <windows.h>
3 use of parameter from containing function
这一般出现在函数内部定义了一些参数和一个类,然后在类内部使用了类外部的参数。可以通过在类内部定义引用,然后构造的时候传递进去解决。
4 使用一些模板函数忘记按引用传参
class X {
public:
//错误,x是临时变量,导致m_x指向一块废内存
//X( map<int, int> x ) : m_x(x) {}
X( map<int, int> & x ) : m_x(x) {}
public:
map<int, int> & m_x;
};
5 用一个数据块来给一个带有0数组的结构体使用,忘记placement new
struct A {
A() { size = 0; }
size_t size;
int objs[0];
};
char buf[MAX_BUFF_LEN];
A* x = static_cast<A*>( buf );
new ( static_cast<void*>( x ) ) A(); // 如果漏了这句,那A的构造函数就不会执行。
6 在有虚表类的构造函数里面调用了memset,导致vtable被改写。要谨记,继承虚函数的类除了类成员本身,还有虚表。
#include <stdio.h>
#include <string.h>
class B;
struct TT {
int a;
char b;
long c;
void print( B& );
};
class A {
public:
virtual void print( TT* x ) = 0;
virtual ~A() {}
};
class B : public A {
public:
B() { memset( this, 0, sizeof(*this) ); }
virtual void print( TT* x ) { printf( "B %d %c %ld\n", x->a, x->b, x->c ); }
};
void TT::print( B& b ) {
b.print( this );
}
int main() {
TT y;
B x;
y.print( x );
return 0;
}
7 用unsigned值判断小于0退出
因为unsigned值不可能小于0,所以成了死循环。
for( unsigned int i = 10; i >= 0; --i ) {
some code here
}
但是也可以利用unsigned的这个性质简化判断
void fun( int i ) {
if( i >= 0 && i < MAXT ) {
some code here
}
}
改为下面的代码:
void fun( int i ) {
if( (unsigned int ) i < MAXT ) {
some code here
}
}