当前位置:   article > 正文

20181111-hight-property-codes

mshtml:add_func_info could not get referenced type info: 80070057
layout title categories tags date description
post
《高质量的C++代码笔记》
blog
C++
开发
2018-11-11 12:59:59 -0800
软件质量是被大多数程序员挂在嘴上而不是放在心上的东西!有多少软件开发人员对正确性、健壮性、可靠性、效率、易用性、可读性(可理解性)、可扩展性、可复用性、兼容性、可移植性等质量属性了如指掌?并且能在实践中运用自如?。

引言

软件质量是被大多数程序员挂在嘴上而不是放在心上的东西! 除了完全外行和真正的编程高手外,初读本书,你最先的感受将是惊慌:“哇!我 以前捏造的 C++/C 程序怎么会有那么多的毛病?”有多少软件开发人员对正确性、健壮性、可靠性、效率、易用性、可读性(可理解性)、可扩展性、可复用性、兼容性、可移植性等质量属性了如指掌?并且能在实践中运用自如?。至少我现在还不是,我只能将平时遇到的一些值得记录的东西记录下来,以供下次翻阅。

从小程序看问题

strcpy的实现可以看出一个人的

  • 编程风格
  • 出错处理
  • 算法复杂度分析
  1. char* strcpy(char* dest, const char* source)
  2. {
  3. char * destcopy = dest;
  4. if((dest == NULL) || (source == NULL))
  5. throw "Invalid Arguments";
  6. while((*dest++=*source++)!= '\0');
  7. return destcopy;
  8. }

文件结构

  1. 声明在头文件.h,定义在源代码文件.cpp或者.c .cc
  2. 为了防止头文件被重复引用,应当用 ifndef/define/endif 结构产生预 处理块。
  3. 用 #include <filename.h> 格式来引用标准库的头文件(编译器将 从标准库目录开始搜索)。用 #include “filename.h” 格式来引用非标准库的头文件(编译器将从用户的工作目录开始搜索)。 �4. 头文件中只存放“声明”而不存放“定义”
  4. 不提倡使用全局变量, 尽量不要在头文件中出现象 extern int value 这 类声明。
  1. /*
  2. * Copyright (c) 2001,上海贝尔有限公司网络应用事业部
  3. * All rights reserved.
  4. *
  5. * 文件名称: filename.h
  6. * 文件标识: 见配置管理计划书
  7. * 摘 要: 简要描述本文件的内容
  8. *
  9. * 当前版本: 1.1
  10. * 作 者: 输入作者(或修改者)名字
  11. * 完成日期: 2001年7月20日
  12. *
  13. * 取代版本: 1.0
  14. * 原作者 : 输入原作者(或修改者)名字
  15. * 完成日期: 2001年5月10日
  16. */

为什么要声明和定义分离:

  1. 通过头文件来调用库功能。在很多场合,源代码不便(或不准)向用户公布,只 要向用户提供头文件和二进制的库即可。用户只需要按照头文件中的接口声明来调用库 功能,而不必关心接口怎么实现的。编译器会从库中提取相应的代码。
  2. 头文件能加强类型安全检查。如果某个接口被实现或被使用时,其方式与头文件 中的声明不一致,编译器就会指出错误,这一简单的规则能大大减轻程序员调试、改错 的负担。
  3. 便于管理。如果代码文件比较多,可以将头文件放到include目录下,源文件放到source目录下,方便分别管理

程序

  1. 在每个类声明之后、每个函数定义结束之后都要加空行
  2. 在一个函数体内,逻揖上密切相关的语句之间不加空行,其它地方应 加空行分隔。
  3. 一行代码只做一件事情,如只定义一个变量,或只写一条语句。
  4. if、 for、 while、 do 等语句自占一行,执行语句不得紧跟其后。不论 执行语句有多少都要加{}。这样可以防止书写失误。
  5. 尽可能在定义变量的同时初始化该变量。如果变量的引用处和其定义处相隔比较远,变量的初始化很容易被忘记。如果引用了未被初始化的变量,可能会导致程序错误。本建议可以减少隐患。

指针声明

修饰符 * 和 & 应该靠近数据类型还是该靠近变量名,是个有争议的活题。 若将修饰符 * 靠近数据类型,例如: int* x; 从语义上讲此写法比较直观,即 x 是 int 类型的指针。 上述写法的弊端是容易引起误解,例如: int* x, y; 此处 y 容易被误解为指针变 量。虽然将 x 和 y 分行定义可以避免误解,但并不是人人都愿意这样做。

命名规则

unix系统中常常采用小写字母+_ 的方式 g_:全局变量 k_:static 变量 m_:class成员变量

类的构造函数、析构函数和赋值函数

每个类只有一个析构函数和一个赋值函数,但可以有多个构造函数(包含一个拷贝 构造函数,其它的称为普通构造函数)。对于任意一个类 A,如果不想编写上述函数, C++编译器将自动为 A 产生四个缺省的函数,如 A(void); // 缺省的无参数构造函数 A(const A &a); // 缺省的拷贝构造函数 ~A(void); // 缺省的析构函数 A & operate =(const A &a); // 缺省的赋值函数

经验

不少难以察觉的程序错误是由于变量没有被正确初始化或清除造成的,而初始化和清除工作很容易被人遗忘。

调试经典

#define stub  fprintf(stderr, "error param in %s:%s:%d\n",  __FUNCTION__, __FILE__, __LINE__);

mutable关键字用来解决常函数中不能修改对象的数据成员的问题

内存对齐

这是因为结构体内存分配有自己的对齐规则,结构体内存对齐默认的规则如下:

  • 分配内存的顺序是按照声明的顺序。
  • 每个变量相对于起始位置的偏移量必须是该变量类型大小的整数倍,不是整数倍空出内存,直到偏移量是整数倍为止。
  • 最后整个结构体的大小必须是里面变量类型最大值的整数倍。

内存对齐https://www.cnblogs.com/suntp/p/MemAlignment.html

OpenCV中16b对齐的内存申请和释放

  1. #define CV_MALLOC_ALIGN 16
  2. /*!
  3. Aligns pointer by the certain number of bytes
  4. This small inline function aligns the pointer by the certian number of bytes by shifting
  5. it forward by 0 or a positive offset.
  6. */
  7. template <typename _Tp>
  8. static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
  9. {
  10. return (_Tp*)(((size_t)ptr + n-1) & -n);
  11. }
  12. /*!
  13. Aligns buffer size by the certain number of bytes
  14. This small inline function aligns a buffer size by the certian number of bytes by enlarging it.
  15. */
  16. static inline size_t alignSize(size_t sz, int n)
  17. {
  18. assert((n & (n - 1)) == 0); // n is a power of 2
  19. return (sz + n-1) & -n;
  20. }
  21. void* fastMalloc( size_t size )
  22. {
  23. uchar* udata = (uchar*)malloc(size + sizeof(void*) + CV_MALLOC_ALIGN);
  24. if(!udata)
  25. return OutOfMemoryError(size);
  26. uchar** adata = alignPtr((uchar**)udata + 1, CV_MALLOC_ALIGN);
  27. adata[-1] = udata;
  28. return adata;
  29. }
  30. void fastFree(void* ptr)
  31. {
  32. if(ptr) {
  33. uchar* udata = ((uchar**)ptr)[-1];
  34. CV_DbgAssert(udata < (uchar*)ptr &&
  35. ((uchar*)ptr - udata) <= (ptrdiff_t)(sizeof(void*)+CV_MALLOC_ALIGN));
  36. free(udata);
  37. }
  38. }

NCNN中使用该code进行内存对齐

内存的作用域,不要在函数中创建临时对象返回

  1. #include <cstdio>
  2. #include <cstring>
  3. ///@brief 模型配置结构体
  4. ///@warning 该结构体在与did_model_set_config一起使用时,一定要先全部填充为0,再设置所需要的field。
  5. /// set_model_config/get_model_config 是对该结构体的浅拷贝
  6. typedef struct net_config_t {
  7. int engine;
  8. ///@brief each engine specific data can be passed to here, such as snpe_runtime, tensorrt_batch_size, ocl_context and so on.
  9. ///@note each engine implementation will cast it to the corresponding runtime type, such as snpe_context_t, ppl_context_t.
  10. /// The lifetime of this pointer should span until create_handle finished, and the memory is managed by users.
  11. void* engine_context;
  12. } net_config_t;
  13. void set_net_config_t(net_config_t* config, int engine_type) {
  14. memset(config, 0, sizeof(net_config_t));
  15. int otherc[] = {1, 0, 5};
  16. config->engine = engine_type;
  17. config->engine_context = (void*)&otherc;
  18. }
  19. int main(int argc, char* argv[]) {
  20. net_config_t config;
  21. // 设置模型加载配置项
  22. set_net_config_t(&config, 3);
  23. fprintf(stderr, "config.engine %d\n", config.engine);
  24. int* context = (int*)config.engine_context;
  25. fprintf(stderr, "config.engine_context[0]=%d\n", context[0]);
  26. fprintf(stderr, "config.engine_context[1]=%d\n", context[1]);
  27. fprintf(stderr, "config.engine_context[2]=%d\n", context[2]);
  28. return 0;
  29. }

第一次运行

config.engine 3 config.engine_context[0]=1286489600 config.engine_context[1]=32624 config.engine_context[2]=1288667592

第二次运行

config.engine 3 config.engine_context[0]=-204200448 config.engine_context[1]=32695 config.engine_context[2]=-202022456

从结果中可以看出engine_context中的内存是一块未初始化的内存空间。这是因为返回的局部数组被释放导致的结果。 这情况可能导致你的程序有不期望的执行结果。尤其是如果采用context[1]作为分支判断条件,本来应该为0或者false, 现在可能是正数,也可能是负数,为0的概率非常小。因此我们要避免这种返回局部变量的情况。

Disable COPY和ASSIGN操作的方法, 将赋值函数和拷贝构造函数显示作为private下

方案 1

  1. // A macro to disallow copy constructor and operator=
  2. // This should be used in the private: declarations for a class.
  3. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\
  4. type(type const &);\
  5. void operator=(type const &)
  6. class TestFactoryBase
  7. {
  8. private:
  9. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
  10. }

方案2

  1. class P {
  2. public:
  3. P(const P &) = delete;
  4. P &operator =(const P &p) = delete;
  5. };

以上两个delete声明禁止复制 能够通过明确的方式显式限定这些特殊方法有助于增强代码的可读性和可维护性

++i和i++的重载代码实现

  1. ClassName& operator++()
  2. {
  3. ++cur;
  4. if(cur == last)
  5. {
  6. set_node(node + 1);
  7. cur = first;
  8. }
  9. return *this;
  10. }
  11. ClassName operator(int)
  12. {
  13. ClassName tmp = *this;
  14. ++*this;
  15. return tmp;
  16. }

unsigned类型的默认转化造成的苦恼

u32Width是unsigned int类型的,在进行计算过程中如果u32Width=2,执行到for (; j <= u32Width - 4; j += 4)的时候,会出现问题: 由于j是size_t类型的, u32Width-4会被转化为unsigned int类型,从而造成该判断可通过,从直观上看来就发生了 j <= -2(实际是j <= 4294967294)是为true的事情了。

  1. const unsigned int blob_len = u32Num * u32Chn * u32Height;
  2. for (size_t i = 0; i < blob_len; ++i) {
  3. size_t j = 0;
  4. for (; j <= u32Width - 4; j += 4) {
  5. dataDstBlob[j] = (dst_type)(ps32Ptr[j] * NNIE_DATA_SCALE_INV);
  6. dataDstBlob[j + 1] = (dst_type)(ps32Ptr[j + 1] * NNIE_DATA_SCALE_INV);
  7. dataDstBlob[j + 2] = (dst_type)(ps32Ptr[j + 2] * NNIE_DATA_SCALE_INV);
  8. dataDstBlob[j + 3] = (dst_type)(ps32Ptr[j + 3] * NNIE_DATA_SCALE_INV);
  9. }
  10. for (; j < u32Width; ++j) {
  11. dataDstBlob[j] = (dst_type)(ps32Ptr[j] * NNIE_DATA_SCALE_INV);
  12. }
  13. dataDstBlob += u32Width;
  14. ps32Ptr += blob->u32Stride / getElemSize(blob->enType);
  15. }

C++中容易忽略的库bitset

bitset是处理进制转换基于bit的算法中简单算法,虽然也可以使用raw的char array替代,但是很多bitset自带的方法,可以让程序飞起来。

  1. #include <iostream>
  2. #include <bitset>
  3. using namespace std;
  4. void increment(std::bitset<5>& bset)
  5. {
  6. for (int i = 0; i < 5; ++i)
  7. {
  8. if(bset[i] == 1)
  9. bset[i] = 0;
  10. else
  11. {
  12. bset[i] = 1;
  13. break;
  14. }
  15. }
  16. }
  17. void method_1(){
  18. for (int i = 0; i < 32; ++i) {
  19. std::bitset<5> bset(i);
  20. std::cout << bset << std::endl;
  21. }
  22. }
  23. int main(int argc, char const *argv[]){
  24. std::bitset<5> bset(0);
  25. for (int i = 0; i < 32; ++i) {
  26. std::cout << bset << std::endl;
  27. increment(bset);
  28. }
  29. return 0;
  30. }

仿函数

仿函数(functor),就是使一个类的使用看上去象一个函数。其实现就是类中实现一个 operator(),这个类就有了类似函数的行为,就是一个仿函数类了。C语言使用函数指针和回调函数来实现仿函数,例如一个用来排序的函数可以这样使用仿函数.在C++里,我们通过在一个类中重载括号运算符的方法使用一个函数对象而不是一个普通函数。

  1. template <typename T>
  2. struct xxx
  3. {
  4. returnType operator()(const T& x)
  5. {
  6. return returnType;
  7. }
  8. }
  9. template<typename T>
  10. class display
  11. {
  12. public:
  13. void operator()(const T &x)
  14. {
  15. cout<<x<<" ";
  16. }
  17. };
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. //int sort_function( const void *a, const void *b);
  4. int sort_function( const void *a, const void *b)
  5. {
  6. return *(int*)a-*(int*)b;
  7. }
  8. int main()
  9. {
  10. int list[5] = { 54, 21, 11, 67, 22 };
  11. qsort((void *)list, 5, sizeof(list[0]), sort_function);//起始地址,个数,元素大小,回调函数
  12. int x;
  13. for (x = 0; x < 5; x++)
  14. printf("%i\n", list[x]);
  15. return 0;
  16. }

仿函数在STL中的定义

要使用STL内建的仿函数,必须包含头文件。而头文件中包含的仿函数分类包括

  1. 算术类仿函数 加:plus 减:minus 乘:multiplies 除:divides 模取:modulus 否定:negate
  1. #include <iostream>
  2. #include <numeric>
  3. #include <vector>
  4. #include <functional>
  5. using namespace std;
  6. int main()
  7. {
  8. int ia[]={1,2,3,4,5};
  9. vector<int> iv(ia,ia+5);
  10. cout<<accumulate(iv.begin(),iv.end(),1,multiplies<int>())<<endl;
  11. cout<<multiplies<int>()(3,5)<<endl;
  12. modulus<int> modulusObj;
  13. cout<<modulusObj(3,5)<<endl; // 3
  14. return 0;
  15. }
  1. 关系运算类仿函数

等于:equal_to 不等于:not_equal_to 大于:greater 大于等于:greater_equal 小于:less 小于等于:less_equal

从大到小排序:

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. using namespace std;
  5. template <class T>
  6. class display
  7. {
  8. public:
  9. void operator()(const T &x)
  10. {
  11. cout<<x<<" ";
  12. }
  13. };
  14. int main()
  15. {
  16. int ia[]={1,5,4,3,2};
  17. vector<int> iv(ia,ia+5);
  18. sort(iv.begin(),iv.end(),greater<int>());
  19. for_each(iv.begin(),iv.end(),display<int>());
  20. return 0;
  21. }
  1. 逻辑运算仿函数

逻辑与:logical_and 逻辑或:logical_or 逻辑否:logical_no

google test的一些疑问:TEST_F与TEST的区别

TEST_F与TEST的区别是,TEST_F提供了一个初始化函数(SetUp)和一个清理函数(TearDown),在TEST_F中使用的变量可以在初始化函数SetUp中初始化,在TearDown中销毁,并且所有的TEST_F是互相独立的,都是在初始化以后的状态开始运行,一个TEST_F不会影响另一个TEST_F所使用的数据。

  1. //A.h
  2. #ifndef A_H
  3. #define A_H
  4. class A
  5. {
  6. private:
  7.   int _a;
  8. public:
  9.   A( int a );
  10.   ~A( );
  11.   void add( int a );
  12.   int getA( );
  13. };
  14. #endif
  15. A.cpp
  16. #include "A.h"
  17. A::A( int a ){
  18.   this->_a = a;
  19. }
  20. A::~A( ){
  21. }
  22. void A::add( int a ){
  23.   this->_a += a;
  24. }
  25. int A::getA( ){
  26.   return this->_a;
  27. }
  • A_test.cpp
  1. //  A_test.cpp
  2. #include "A.h"
  3. #include <gtest/gtest.h>
  4. class A_test : public testing::Test {
  5. protected:
  6.   A* _p_a;
  7.   virtual void SetUp( ){   //初始化函数
  8.     this->_p_a = new A( 1 );
  9.   }
  10.   virtual void TearDown( ){  //清理函数
  11.     delete this->_p_a;
  12.   }
  13. };
  14. //第一个测试,参数A_test是上面的那个类,第二个参数FirstAdd是测试名称
  15. TEST_F( A_test,FirstAdd ){    
  16.   EXPECT_EQ( 1,_p_a->getA( ) );
  17.   _p_a->add( 3 );
  18.   EXPECT_EQ( 4,_p_a->getA( ) );
  19. }
  20. //第二个测试
  21. TEST_F( A_test,SecondAdd ){
  22.   EXPECT_EQ( 1,_p_a->getA( ) );
  23.   _p_a->add( 5 );
  24.   EXPECT_EQ( 6,_p_a->getA( ) );
  25. }
  26. /*
  27. 上面的两个测试都是在SetUp函数执行后的状态下执行,也就是说在执行任意一个TEST_F时 _p_a->_a 的值都是初始值1
  28. */
  • main.cpp
  1. #include <gtest/gtest.h>
  2. int main(int argc, char * argv[])
  3. {
  4.   testing::InitGoogleTest(&argc, argv);
  5.   return RUN_ALL_TESTS();
  6. }
  1. #include <unistd.h>
  2. #include <sys/time.h>
  3. #include <time.h>
  4. #define __TIC__() \
  5. struct timeval __timing_start, __timing_end; \
  6. gettimeofday(&__timing_start, NULL);
  7. #define __TOC__() \
  8. do { \
  9. gettimeofday(&__timing_end, NULL); \
  10. double __timing_gap = (__timing_end.tv_sec - \
  11. __timing_start.tv_sec) * \
  12. 1000.0 + \
  13. (__timing_end.tv_usec - \
  14. __timing_start.tv_usec) / \
  15. 1000.0; \
  16. fprintf(stdout, "TIME(ms): %lf\n", __timing_gap); \
  17. } while (0)

看看gtest的工作流程

  • 入口
  1. //第一个测试,参数A_test是上面的那个类,第二个参数FirstAdd是测试名称
  2. TEST(A_test, FirstAdd){    
  3.   EXPECT_EQ( 1,_p_a->getA( ) );
  4.   _p_a->add( 3 );
  5.   EXPECT_EQ( 4,_p_a->getA( ) );
  6. }
  7. // Define this macro to 1 to omit the definition of TEST(), which
  8. // is a generic name and clashes with some other libraries.
  9. #if !GTEST_DONT_DEFINE_TEST
  10. # define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name)
  11. #endif
  12. #define GTEST_TEST(test_case_name, test_name)\
  13. GTEST_TEST_(test_case_name, test_name, \
  14. ::testing::Test, ::testing::internal::GetTestTypeId())
  • 首先看看函数中调用的一个宏的实现
  1. // Expands to the name of the class that implements the given test.
  2. #define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
  3. test_case_name##_##test_name##_Test
  4. // Helper macro for defining tests.
  5. // 这个宏声明了一个继承自parent_class ::testing::Test的类,然后对这个类的属性test_info_进行赋值
  6. #define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\
  7. class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
  8. public:\
  9. GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\
  10. private:\
  11. virtual void TestBody();\
  12. static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\
  13. GTEST_DISALLOW_COPY_AND_ASSIGN_(\
  14. GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\
  15. };\
  16. /*这个宏声明了一个继承自parent_class ::testing::Test的类,然后对这个类的属性test_info_进行赋值*/\
  17. ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\
  18. ::test_info_ =\
  19. ::testing::internal::MakeAndRegisterTestInfo(\
  20. #test_case_name, #test_name, NULL, NULL, \
  21. (parent_id), \
  22. parent_class::SetUpTestCase, \
  23. parent_class::TearDownTestCase, \
  24. new ::testing::internal::TestFactoryImpl<\
  25. GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\
  26. // 实现我们的这个TestBody\
  27. void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
  • 看一下MakeAndRegisterTestInfo函数
  1. TestInfo* MakeAndRegisterTestInfo(
  2. const char* test_case_name,
  3. const char* name,
  4. const char* type_param,
  5. const char* value_param,
  6. TypeId fixture_class_id,
  7. SetUpTestCaseFunc set_up_tc,
  8. TearDownTestCaseFunc tear_down_tc,
  9. TestFactoryBase* factory) {
  10. TestInfo* const test_info =
  11. new TestInfo(test_case_name, name, type_param, value_param,
  12. fixture_class_id, factory);
  13. // 添加测试用例信息到UnitTestImpl的testcase_中
  14. GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
  15. return test_info;
  16. }
  • AddTestInfo试图通过测试用例名等信息获取测试用例,然后调用测试用例对象去新增一个测试特例——test_info。 这样我们在此就将测试用例和测试特例的关系在代码中找到了关联。
  1. // Finds and returns a TestCase with the given name. If one doesn't
  2. // exist, creates one and returns it. It's the CALLER'S
  3. // RESPONSIBILITY to ensure that this function is only called WHEN THE
  4. // TESTS ARE NOT SHUFFLED.
  5. //
  6. // Arguments:
  7. //
  8. // test_case_name: name of the test case
  9. // type_param: the name of the test case's type parameter, or NULL if
  10. // this is not a typed or a type-parameterized test case.
  11. // set_up_tc: pointer to the function that sets up the test case
  12. // tear_down_tc: pointer to the function that tears down the test case
  13. TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
  14. const char* type_param,
  15. Test::SetUpTestCaseFunc set_up_tc,
  16. Test::TearDownTestCaseFunc tear_down_tc) {
  17. // Can we find a TestCase with the given name?
  18. const std::vector<TestCase*>::const_iterator test_case =
  19. std::find_if(test_cases_.begin(), test_cases_.end(),
  20. TestCaseNameIs(test_case_name));
  21. if (test_case != test_cases_.end())
  22. return *test_case;
  23. // No. Let's create one.
  24. TestCase* const new_test_case =
  25. new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
  26. // Is this a death test case?
  27. if (internal::UnitTestOptions::MatchesFilter(test_case_name,
  28. kDeathTestCaseFilter)) {
  29. // Yes. Inserts the test case after the last death test case
  30. // defined so far. This only works when the test cases haven't
  31. // been shuffled. Otherwise we may end up running a death test
  32. // after a non-death test.
  33. ++last_death_test_case_;
  34. test_cases_.insert(test_cases_.begin() + last_death_test_case_,
  35. new_test_case);
  36. } else {
  37. // No. Appends to the end of the list.
  38. test_cases_.push_back(new_test_case);
  39. }
  40. test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
  41. return new_test_case;
  42. }

Reference

来自GTEST文档中的内容,方便后续查看

Introduction: Why Google C++ Testing Framework?

Google C++ Testing Framework helps you write better C++ tests.

No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, Google Test can help you.

So what makes a good test, and how does Google C++ Testing Framework fit in? We believe:

  1. Tests should be independent and repeatable. It's a pain to debug a test that succeeds or fails as a result of other tests. Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging.
  2. Tests should be well organized and reflect the structure of the tested code. Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base.
  3. Tests should be portable and reusable. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral. Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations. (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.)
  4. When tests fail, they should provide as much information about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle.
  5. The testing framework should liberate test writers from housekeeping chores and let them focus on the test content. Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them.
  6. Tests should be fast. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.

Since Google C++ Testing Framework is based on the popular xUnit architecture, you'll feel right at home if you've used JUnit or PyUnit before. If not, it will take you about 10 minutes to learn the basics and get started. So let's go!

Note: We sometimes refer to Google C++ Testing Framework informally as Google Test.

Setting up a New Test Project

To write a test program using Google Test, you need to compile Google Test into a library and link your test with it. We provide build files for some popular build systems: msvc/ for Visual Studio, xcode/ for Mac Xcode, make/ for GNU make, codegear/ for Borland C++ Builder, and the autotools script (deprecated) and CMakeLists.txt for CMake (recommended) in the Google Test root directory. If your build system is not on this list, you can take a look at make/Makefile to learn how Google Test should be compiled (basically you want to compile src/gtest-all.cc with GTEST_ROOT and GTEST_ROOT/include in the header search path, where GTEST_ROOT is the Google Test root directory).

Once you are able to compile the Google Test library, you should create a project or build target for your test program. Make sure you have GTEST_ROOT/include in the header search path so that the compiler can find "gtest/gtest.h" when compiling your test. Set up your test project to link with the Google Test library (for example, in Visual Studio, this is done by adding a dependency on gtest.vcproj).

If you still have questions, take a look at how Google Test's own tests are built and use them as examples.

Basic Concepts

When using Google Test, you start by writing assertions, which are statements that check whether a condition is true. An assertion's result can be success, nonfatal failure, or fatal failure. If a fatal failure occurs, it aborts the current function; otherwise the program continues normally.

Tests use assertions to verify the tested code's behavior. If a test crashes or has a failed assertion, then it fails; otherwise it succeeds.

A test case contains one or many tests. You should group your tests into test cases that reflect the structure of the tested code. When multiple tests in a test case need to share common objects and subroutines, you can put them into a test fixture class.

A test program can contain multiple test cases.

We'll now explain how to write a test program, starting at the individual assertion level and building up to tests and test cases.

Assertions

Google Test assertions are macros that resemble function calls. You test a class or function by making assertions about its behavior. When an assertion fails, Google Test prints the assertion's source file and line number location, along with a failure message. You may also supply a custom failure message which will be appended to Google Test's message.

The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

Since a failed ASSERT_* returns from the current function immediately, possibly skipping clean-up code that comes after it, it may cause a space leak. Depending on the nature of the leak, it may or may not be worth fixing - so keep this in mind if you get a heap checker error in addition to assertion errors.

To provide a custom failure message, simply stream it into the macro using the << operator, or a sequence of such operators. An example:

  1. ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
  2. for (int i = 0; i < x.size(); ++i) {
  3. EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
  4. }

Anything that can be streamed to an ostream can be streamed to an assertion macro--in particular, C strings and string objects. If a wide string (wchar_t*, TCHAR* in UNICODE mode on Windows, or std::wstring) is streamed to an assertion, it will be translated to UTF-8 when printed.

Basic Assertions

These assertions do basic true/false condition testing.

Fatal assertion Nonfatal assertion Verifies
ASSERT_TRUE(condition); EXPECT_TRUE(condition); condition is true
ASSERT_FALSE(condition); EXPECT_FALSE(condition); condition is false

Remember, when they fail, ASSERT_* yields a fatal failure and returns from the current function, while EXPECT_* yields a nonfatal failure, allowing the function to continue running. In either case, an assertion failure means its containing test fails.

Availability: Linux, Windows, Mac.

Binary Comparison

This section describes assertions that compare two values.

Fatal assertion Nonfatal assertion Verifies
ASSERT_EQ(val1, val2); EXPECT_EQ(val1, val2); val1 == val2
ASSERT_NE(val1, val2); EXPECT_NE(val1, val2);
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/224435?site
推荐阅读
相关标签
  

闽ICP备14008679号