败犬日报 2025-03-12
1. 深入理解Linux内存优化:如何使用屏障提升性能 - 玩转Linux内核的文章 - 知乎
https://zhuanlan.zhihu.com/p/29453496671
2. 模板参数能不能部分指定部分推导
cpp
struct X {};
template <typename A, typename B>
void func(B b);
int main() { func<X>(0); }
没问题,调的是 void func<X, int>(int)
。
cpp
struct X {
using x = char;
};
template <typename A, typename B = A::x>
void func(B b);
int main() { func<X>(0.0f); }
这里 B 会先推导再填默认实参,所以调的是 void func<X, float>(float)
。
想要 A::x
直接写:
cpp
template <typename A>
void func(A::x b);
reference: https://eel.is/c++draft/temp.deduct#general-5.sentence-2
3. gnu::pure
会带来什么优化
比如循环内函数求值提到外面,或者:
cpp
if (x > func()) {
y = func();
}
4. C 的资源释放问题
函数退出前要把之前的 malloc 全都 free 了,如果函数复杂就会有大量重复 free。
一般要用 goto 来解决,例如:
cpp
void func() {
int *a, *b, *c;
a = (int *)malloc(sizeof(int));
if (a == NULL) {
goto a_fail;
}
b = (int *)malloc(sizeof(int));
if (b == NULL) {
goto b_fail;
}
c = (int *)malloc(sizeof(int));
if (c == NULL) {
goto c_fail;
}
free(c);
c_fail:
free(b);
b_fail:
free(a);
a_fail:
}
如果项目禁止了 goto,可以用 attribute cleanup,类似 C++ 的 RAII。
5. 尾随对象无法放进 std::tuple
尾随对象是包含柔性数组的对象:
cpp
struct A {
int x;
int arr[];
};
尾随对象没有默认拷贝构造、移动构造,以及不能继承(因为柔性数组总是在对象末尾)。std::tuple
的实现采用了继承,所以就会编译报错。