Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

c++规范 #2

Open
yanminhui opened this issue Jan 22, 2019 · 0 comments
Open

c++规范 #2

yanminhui opened this issue Jan 22, 2019 · 0 comments

Comments

@yanminhui
Copy link

yanminhui commented Jan 22, 2019

示例1

// FaceppApi.hpp

#include <stdio.h>  //  [1]

class FaceppApi 
{
protected:
    const char * key; // Api_key         [2]
    const char * secret; // Api_secret
};

[1] 一般使用 #include <cstdio> 代替 #include <stdio.h>

The ".h" headers dump all their names into the global namespace, whereas the newer forms keep their names in namespace std. Therefore, the newer forms are the preferred forms for all uses except for C++ programs which are intended to be strictly compatible with C.

@see Standard C++ C-Library Subset Header Strategy

[2] 在类中使用指针的危险性

FaceppApi 中使用指针为浅复制,当使用常量指针转递参数给构造函数没有问题,作为 C++ 的开发者会选择 std::string ,为了适配库,可能以 std::string.c_str() 形式传递参数给构造函数,往往出现参数已经失效,引用了一个无效的指针。

示例2

// Utils/CurlPost.hpp

#ifndef CurlPost_hpp
#define CurlPost_hpp

#include <iostream>
#include <map>

using namespace std;  // [3]

class CurlPost 
{
    public :
    void doPost(const char * URL, map<const char* , const char*> params);  // [4]
};

#endif /* CurlPost_hpp */

[3] 在头文件中引入命名空间 std 容易引发名字冲突

难以保证我们在开发过程中不效仿标准库的命名规则,在头文件中引入命名空间 std,只要包含了它,后续所有代码都表明使用命名空间内的代码,万一自己命名了相同的标识符会产生冲突。

[4] 与类成员无关的函数可以独立

在类 CurlPost 中的 doPost 并没有使用类的任何数据,这个方法导致在调用处创建一个临时对象,将它声明为静态函数(CurlPost::doPost(...))或命名空间(curlpost::doPost(...))内的自由函数,免于创建临时对象。

[5] 建议: 库加上自己的命名空间,免于与用户代码冲突。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant