Yanyg - Software Engineer

C++ 1X 常用语法

目录

1 基本语法示例

// 1. prevent recursive include
#pragma once

#include <string>

class Code
{
  // ...
};

class Example
{
public:
  Example() = default; // default constructor
  ~Example() = default;
  Example(int i, int j);
  // delegating constructor
  Example(int i) : Example(i, 100) {}
  Example(const Example &other);
  // move constructor, noexception
  Example(Example &&other) noexcept;
  Example& operator=(const Example &other);
  // move assignment
  Example& operator=(Example &&other) noexcept;
private:
  int mInterval = 100; // init in place
  std::string mSignature = "ExampleObj";
};

// disallow derive from the class
class Example final : public IoStream
{
public:
  void Print(...) override; // IoStream MUST have virtual member function Print.
};

enum class State: uint8_t
{
  INIT = 0,
  CHECKIN = 1,
  SEALED = 2,
};
static_assert(sizeof(State) == 1, "State is Uint8");

enum class FileType
{

  REPLICATION = 1,
  EC = 2,
};

// alias name
using Closure = ::google::protobuf::Closure;

// compiling const
constexpr uint32_t MAGIC = 0xf8f8f8f8;

uint64_t var = 100;
auto var2 = var;

// initialization list
std::vector<int> intVec = {1, 2, 3};

Example* pObj = nullptr;

// right angle brackets
using TypeVec = std::map<int, std::vector<std::string>>;

// iterate stl
for (const auto & e : vec)
{
  // ...
}

// __thread to thread_local and allow non-pod type;
thread_local std::vector<int> tlsVec;

// STL
std::mutex;
std::lock_guard<std::mutex>;
std::conditional_variable;
std::atomic<int>;
std::tuple<int, long, string>;
std::array<int>;
std::unordered_set, std::unordered_map, ...;
std::unique_ptr<Obj>;
std::chrono;
std::thread;

2 Memory Model

2.1 乱序

  • 编译器单线程优化;
  • CPU乱序执行;
  • CPU L1/L2/L3 Cache;
  • 多线程共享,通过原子操作或锁,告知编译器/CPU保证一致性;
// init
int x = 0;
int y = 0;

// Thread 1:
x = 1;
y = 1;

// Thread 2:
if (y == 1)
{
  ASSERT(x == 1);
}