栈上数组

// 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);

未完待续...

本文固定链接: http://www.js-code.com/cpp/cpp_60229.html