C++ 常用代码片段

  1. 查看auto变量的真实类型
const int var = 0;
// 那么可以通过定义如下代码来查看var的真是类型:const int
template<typename T> struct TD;
TD<decltype(var)> td;//此时会出现编译错误,错误信息中可以看到var的类型
  1. 禁用/使用class默认函数
// Helper to delete copy constructor & copy-assignment operator
#define DISABLE_COPY_MOVE_ASSIGN(name)   \
  name(const name&) = delete;            \
  name& operator=(const name&) = delete; \
  name(name&&) = delete;                 \
  name& operator=(name&&) = delete

// Helper to declare copy constructor & copy-assignment operator default
#define DEFAULT_COPY_MOVE_ASSIGN(name)    \
  name(const name&) = default;            \
  name& operator=(const name&) = default; \
  name(name&&) = default;                 \
  name& operator=(name&&) = default

使用例子:

class Image{
public: 
	Image(const std::string& name){}
	DISABLE_COPY_MOVE_ASSIGN(Image);
};

“3/5法则”

默认C++在定义一个类时,拷贝构造函数(copy constructor)、拷贝赋值(copy assignment)函数和析构函数这三个函数如果定义了其中一个, 那么剩下的两个也需要定义.所以我们称此为“C++三法则", c++11后增加了(move constructor, move assignment)后变成了5法则. 一旦我们的类自定义了析构函数,那么要么去实现另外的2个或者4个特殊函数, 要么把这些特殊函数设置为delete.

struct S {
    S(); // default constructor
        // does not affect other special member functions
    ~S();

    // If you define any of the following, you must deal with
    // all the others.
    S(const S &); // 拷贝构造
    S &operator=(const S &); // 拷贝赋值

    S(S&&);     // 移动构造 
    S &operator=(S &&); //  移动赋值 
};

当你不知道怎么去处理它们的时候,=delete 对于这些特殊的成员函数来说是一个非常安全的处理方法. 类似的, 如果父类自定义了虚构函数, 那么子类也需要遵循上面的3/5法则, 要么delete, 要么实现.

当你在声明带有虚函数的基类时,你也应该遵循”五法则“:

class Person{
public:
  Person(){buff = new char[30];}
  ~Person(){delete buff;}
  private:
  char* buff = nullptr;
};
int main(){
Person p1;
Person p2 = p1; 
}//p1, p2析构时会两次delete buff.crash....

gdb使用

# 调试带参数程序
# cmakelist添加:-ggdb -O0 -g
gdb --tui --args a.out --video /dev/video0
# 1. 添加断点
# b src/test.cpp:20 , 在某行断点
# b src/test.cpp:20 if num==3 # 条件断点, num为20行里的变量
# 2.重启程序
# r
# p a # 打印变量a
# w # 查看堆栈
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值