鲜为人知的C++特性

翻译至:https://madebyevan.com/obscure-cpp-features/

小括号的写法
以下写法等价:
ptr[3]
*(ptr + 3)
*(3 + ptr)
3[ptr]

Most vexing parse
这个问题,可以通过加小括号规避

运算符 字母和符号
The tokens and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq, <%, %>, <:, and :> can be used instead of the symbols &&, &=, &, |, ~, !, !=, ||, |=, ^, ^=, {, }, [, and ]
考虑有些键盘上缺少某些符号

重载关键字,一些情况下可能有用

Placement new
定位new,优势:
1)在已分配好的内存上进行对象的构建,构建速度快。
2)已分配好的内存可以反复利用,有效的避免内存碎片问题。

#include <iostream>
using namespace std;

struct Test {
  int data;
  Test() { cout << "Test::Test()" << endl; }
  ~Test() { cout << "Test::~Test()" << endl; }
};

int main() {
  // Must allocate our own memory
  Test *ptr = (Test *)malloc(sizeof(Test));

  // Use placement new
  new (ptr) Test;

  // Must call the destructor ourselves
  ptr->~Test();

  // Must release the memory ourselves
  free(ptr);

  return 0;
}

成员函数的引用修饰符

#include <iostream>

struct Foo {
  void foo() & { std::cout << "lvalue" << std::endl; }
  void foo() && { std::cout << "rvalue" << std::endl; }
};

int main() {
  Foo foo;
  foo.foo(); // Prints "lvalue"
  Foo().foo(); // Prints "rvalue"
  return 0;
}

指向成员的指针操作符

实例的静态方法

struct Foo {
  static void foo() {}
};

// These are equivalent
Foo::foo();
Foo().foo();

重载++和--

struct Number {
  Number &operator ++ (); // Generate a prefix ++ operator
  Number operator ++ (int); // Generate a postfix ++ operator
};

规则:添加一个int,表示后置
后置方式会生成一个临时对象,效率低
对基础类型来说,前置和后置效率一样

操作符重载和检查顺序
重载,(逗号),||或者&&操作符会引起混乱,因为它打破了正常的检查规则。
尽量不要重载这几个操作符

函数作为模板参数
编译器在实例化模板代码时内联调用特定的函数以获得更高效的执行

模板作为模板参数
typename

posted @ 2022-02-08 17:54  天下太平  阅读(33)  评论(0编辑  收藏  举报