caffe 源码中体现的c++编程规范

google C++ stylehttp://zh-google-styleguide.readthedocs.io/en/latest/google-cpp-styleguide/

caffe 是非常优秀的、标准的c++代码。用了google编程规范。值得学习。总结一下caffe的基本语法细节。

1、常成员函数

#include <iostream>
using namespace std;

class Blob{
    public:
        int count() {  XXX!!!  //Note: 正确方法 int count( ) const {
            cout <<"I am not const function " << endl;
            return 0;
        }   
};

void func( Blob const& blob ){  //这里声明的是常引用的对象,意味着这个对象只可以调用常成员函数。因为非const函数都有可能修改私有变量。
    blob.count();
}                                                                                                              
int main(int argc, char ** argv)
{
    Blob w;
    func(w);
    return 0;
}//编译会出现error: passing xxx as 'this' argument of xxx discards qualifiers

修改:" namely you're calling a non-const member function on const object which is not    
      allowed because non-const member functions make NO PROMISE not to modify the 
      object; so the compiler is going to make a safe assumption that function() might  
      attempt to modify the object but at the same time, it also notices that the   
      object is const; so any attempt to modify the const object should be an error.   
      Hence compiler generates error message.

2、const问题,Google为了增加代码的可读性,明确要求:

2—1不做修改的量(涵盖函数体内、函数参数列表),必须以const标记。
2—2相对的,对于那些改变的量,可选择用mutable标记

3、caffe中有很多层:基类Layer。

我们当前有一个基类指针Layer* layer;
在程序运行之前,计算机并不知道这个指针究竟要指向何种派生类。是卷积层?Pooling层?ReLU层?
caffe 用了c++中的精髓:多态!(实现方式:函数指针)。

typedef boost::shared_ptr< Layer<Dtype> > (*NEW_FUNC)(const LayerParameter& );

经过typdef之后,NEW_FUNC就可以指向函数:

boost::shared_ptr< Layer<Dtype> > xxx(const LayerParameter& x);
NEW_FUNC yyy=boost::shared_ptr< Layer<Dtype> > xxx(const LayerParameter& x);

yyy();  //相当于xxx()
xxx();

4caffe中的mutable变量

实际上c++中的mutable变量是为了解决:在const声明的函数中去修改变量。
因为呀,const声明的函数是不可以修改变量的数值的。

#include <iostream>                                                                                              
using namespace std;

class a{
    public:
        std::size_t length(int x, int y) const; //常函数
    public:
        char * p;
        mutable std::size_t textLength = 4;  //这个变量就可以任意修改,即使是声明了const
        bool lengthIsValid;
};

std::size_t a::length(int x,int y) const
{     //这个例子不太好,仅仅为了说明mutable 用法
    textLength = 5;
    return textLength;

}


int main()
{
    a A;
    cout <<A.textLength << endl;  //4
    A.length(1,2);
    cout << A.textLength<< endl;   //5
    return 0;
}

5、一个图片

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值