C++编程调试秘笈----一些杂项(二)

2014-11-24 08:33:25 · 作者: · 浏览: 1
T operator / (T x)
{
SCPP_ASSERT(x != 0, "Attempt to divide by 0");
return data_ / x;
}
private:
T data_;
};
typedef long long int64;
typedef unsigned long long unsigned64;
typedef TNumber Int;
typedef TNumber Unsigned;
typedef TNumber Int64;
typedef TNumber Unsigned64;
typedef TNumber Float;
typedef TNumber Double;
typedef TNumber Char;
class Bool
{
public:
Bool(bool x = false)
:data_(x)
{
}
operator bool () const
{
return data_;
}
Bool& operator = (bool x)
{
data_ = x;
return *this;
}
Bool& operator &= (bool x)
{
data_ &= x;
return *this;
}
Bool& operator |= (bool x)
{
data_ |= x;
return *this;
}
private:
bool data_;
};
inline std::ostream& operator << (std::ostream& os, Bool b)
{
if (b)
{
os << "True";
}
else
{
os << "False";
}
return os;
}
#define SCPP_DEFINE_COMPARISON_OPERATORS(Class) \
bool operator < (const Class& that) const { return CompareTo(that) < 0; } \
bool operator > (const Class& that) const { return CompareTo(that) > 0; } \
bool operator ==(const Class& that) const { return CompareTo(that) ==0; } \
bool operator <=(const Class& that) const { return CompareTo(that) <=0; } \
bool operator >=(const Class& that) const { return CompareTo(that) >=0; } \
bool operator !=(const Class& that) const { return CompareTo(that) !=0; }
#endif
测试代码(vs2012+win7环境):
[cpp]
#include "stdafx.h"
#include "scpp_assert.h"
#include "iostream"
#include "scpp_vector.h"
#include "scpp_array.h"
#include "scpp_matrix.h"
#include "algorithm"
#include "scpp_types.h"
#include "scpp_refcountptr.h"
#include "scpp_scopedptr.h"
#include "scpp_ptr.h"
#include "string"
#define STUDENTAGE 10
class Student
{
public:
Student(int age)
{
SCPP_ASSERT(age > 0, "number must be large 0");
age_ = age;
}
int CompareTo(const Student& that) const
{
if (this->age_ > that.age_)
{
return 1;
}
else if(this->age_ == that.age_)
{
return 0;
}
else
{
return -1;
}
}
SCPP_DEFINE_COMPARISON_OPERATORS(Student);
private:
int age_;
};
int _tmain(int argc, _TCHAR* argv[])
{
Student studentFirst(STUDENTAGE);
Student studentSecond(STUDENTAGE);
if (studentFirst >= studentSecond)
{
std::cout << "(studentFirst > studentSecond) && (studentFirst == studentSecond)" << std::endl;
}
return 0;
}
4、使用标准C函数库的错误
C函数库中,在好几个方面都是不安全的,还可能导致程序崩溃
比如使用stdio.h中想sprintf()这样的函数可能会有下面的问题:
a、有些函数接受字符数组的指针(char *),如果向他们传递一个NULL而不是指向合法的C字符串的指针,将会崩溃(比如strlen(NULL);就可以秒掉程序)
b、有些函数将写入一个缓冲区,他们可能会改写越过缓冲区尾部的内存,从而导致不可预料的程序行为
.....
上面的问题,可以这样处理:
a、提供执行所有必要安全检查的版本,并按照与处理空字符串的相同方式处理NULL指针
b、对于不能牺牲字符串操作速度的应用程序,提供只在测试时才激活的临时安全检查的函数版本
......
但是,这些问题最好的解决方案是不用C字符串函数库,而是改用C++所提供的类,比如:
strlen(name)可以改用name.size(),对于strcpy()可以仅仅 使用字符串赋值操作符;strcat()或strncat()可以改用:
[cpp]
int _tmain(int argc, _TCHAR* argv[])
{
std::ostringstream buffer;
buffer << "zeng";
buffer << "raoli";
std::stri