败犬日报 2025-11-16
败犬日报 2025-11-16
1. 右值引用传参时发生了什么
cpp
#include <utility>
void foo(int&&) {}
int bar() { return 0; }
int main() {
foo(114);
foo(bar());
int x = 514;
foo(std::move(x));
}foo(114) 中的 114 是一个 prvalue(纯右值),先发生了临时量实质化,实质化是指 prvalue 转换为了 xvalue(将亡值)。然后传给 foo。
foo(bar()) 的 bar() 也是 prvalue,发生的事情同上。
foo(std::move(x)) 里的 std::move 将 lvalue(左值)转换为 xvalue,然后传给 foo。
2. std::vector<std::atomic<T>> 会发生什么
cpp
#include <atomic>
#include <vector>
int main() {
std::vector<std::atomic<int>> a(10);
a[0] = 1;
a.pop_back();
a.clear();
// a.push_back(2); // 编译报错
// a.resize(2); // 编译报错
}可以用但有限制。
我们知道 std::atomic 不可复制不可移动。由于 push_back 和 resize 之类的操作会导致 vector 扩容,就需要复制或移动元素,所以这些操作都会编译失败。