C++ 現代編程風格速查表

棧上數組

// naive:
int arr[10];
memset(arr, 0, sizeof(a));
// modern:
// #include <array>
std::array<int, 10> arr;
arr.fill(0);

堆上數組

// naive:
int *arr = new int[10];
memset(arr, 0, 10 * sizeof(int));
// modern:
// #include <vector>
std::vector<int> arr(10);

字符串

// naive:
char str[] = "Hello, C++!";
// modern:
// #include <string>
std::string str = "Hello, C++!";
// or auto str = "Hello, C++!"s;

指向棧的指針

// naive:
int ival;
int *p = &ival;
// modern:
int ival;
int &rval = ival;

堆上對象

// naive:
MyClass *obj = new MyClass;
obj->someMethod(args);
// modern:
auto obj = std::make_unique<MyClass>();
// or auto obj = std::make_shared<MyClass>();
obj->someMethod(args);

函數指針

// naive:
typedef int (*func_t)(int, int);
func_t func = some_func;
// modern:
// #include <function>
std::function<int(int, int)> func = some_func;

函數對象

// naive:
struct func_t
{
    int operator() (int arg1, int arg2)
    {
        // statements
    }
};

func_t func;
// modern:
// #include <function>
std::function<int(int, int)> func
    = [](int arg1, int arg2)
    {
        // statements
    };

宏定義常量

// naive:
#define PI 3.14
// modern:
const double PI = 3.14;

宏定義類型

// naive:
#define uint unsigned int
// modern:
typedef unsigned int uint;
// or using uint = unsigned int;

宏定義函數

// naive:
#define max(a, b) ((a)>(b)?(a):(b))
// modern:
template<T>
inline T max(T a, T b)
{
    return a>b? a: b;
}

原生類型轉換

// naive:
int ival;
double dval = (double)ival;

char *pc1 = ...;
const char *cpc = (char *)pc1;
char *pc2 = (const char *)cpc;

Derived *pd1 = ...;
Base *pb = (Base *)pd1;
Derived *pd2 = (Derived *)pb;

void *pv1 = ...;
long lval = (long)pv1;
void *pv2 = (void *)lval;
// modern:
int ival;
double dval = static_cast<double>(ival);

char *pc1 = ...;
const char *cpc = const_cast<const char *>(pc1);
char *pc2 = const_cast<char *>(cpc);

Derived *pd1 = ...;
Base *pb = dynamic_cast<Base *>(pd1);
Derived *pd2 = dynamic_cast<Derived *>(pb);

void *pv1 = ...;
long lval = reinpreter_cast<long>(pv1);
void *pv2 = reinpreter_cast<void *>(lval);

線程

// naive:
// #include <pthread.h>
pthread_t tid;
pthread_create(&tid, func, arg);
// modern:
// #include <thread>
std::thread thr(func, arg);

未完待續...數組

相關文章
相關標籤/搜索