C++进阶偏基础:5个常用语法点,配上可直接运行的最小示例。

22 阅读1分钟

初始化列表

class A {
public:
    A(int x) : a(x), b(x) {}
private:
    int a;
    const int b;
};

 

const 成员函数

class Counter {
public:
    int get() const { return n; }
    void inc() { n++; }
private:
    int n = 0;
};
const Counter c;
c.get();  // OK
// c.inc(); // 编译报错

 

返回值优化(RVO)

#include <string>
std::string f() {
    std::string s = "hello";
    // return std::move(s); // 没必要
    return s; // 触发 RVO
}

 

std::optional

#include <optional>
std::optional<int> find() {
    // if (...) return 42;
    return std::nullopt;
}
auto x = find();
if (x) { /* 使用 *x */ }

 

结构化绑定

#include <tuple>
std::tuple<int, std::string> f() { return {42, "hi"}; }
auto [x, s] = f();