Loading... # 1 async ```cpp #include <iostream> #include <string> #include <future> int main() { std::string x = "x"; std::async(std::launch::async, [&x]() { x = "y"; }); std::async(std::launch::async, [&x]() { x = "z"; }); std::cout << x; } ``` 输出: ```cpp z ``` ## 解析 `std::async`生成`std::future`,它的析构将会阻塞直至`async`完成。由于没有赋值,因此两次产生的`std::future`对象均是临时变量,将会在表达式完成后析构,因此第一个`async`的阻塞将会使两次调用有序,最终结果为`z`。 # 2 有符号类型溢出 ```cpp #include <iostream> #include <limits> int main() { int i = std::numeric_limits<int>::max(); std::cout << ++i; } ``` 答案: <span style='color:red'>UB</span>。 ## 解析 **Signed integer** overflow is undefined behaviour according to the standard *[§[expr]¶4](https://timsong-cpp.github.io/cppwp/n4659/expr#4)* : "If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined." Most implementations will just wrap around, so if you try it out on your machine, you will probably see the same as if you had done `std::cout << std::numeric_limits<int>::min();` # 3 虚函数在构造和析构时 ```cpp #include <iostream> struct A { A() { foo(); } virtual ~A() { foo(); } virtual void foo() { std::cout << "1"; } void bar() { foo(); } }; struct B : public A { virtual void foo() { std::cout << "2"; } }; int main() { B b; b.bar(); } ``` 答案: ```cpp 121 ``` ## 解析 只有`b.bar()`会调用`B`的虚函数,而在`A`的构造和析构时都不会,因为那些时候都没有**基类对象**,而是纯粹的操作父类对象`A`。 # 4 循环跳转 ```cpp #include <iostream> int main() { int i=1; do { std::cout << i; i++; if(i < 3) continue; } while(false); return 0; } ``` 答案: ```cpp 1 ``` ## 解答 `continue`**会跳转到循环末尾而非开始**。 # 5 initializer_list的内存 ```cpp #include <initializer_list> #include <iostream> class C { public: C() = default; C(const C&) { std::cout << 1; } }; void f(std::initializer_list<C> i) {} int main() { C c; std::initializer_list<C> i{c}; f(i); f(i); } ``` 答案: ```cpp 1 ``` ## 解答 > the `std::initializer_list<E>` object is constructed to refer to that array. > > Copying an initializer list does not copy the underlying elements. 初始化列表本质是一个轻量级的**代理对象**,它的背后实现可以是一个**临时的**`const T[N]`的**首尾指针**。 # 6 数组的构造与析构 ```cpp #include <iostream> class show_id { public: ~show_id() { std::cout << id; } int id; }; int main() { delete[] new show_id[3]{ {0}, {1}, {2} }; } ``` 答案: ```cpp 210 ``` ## 解析 数组对象构造**有序**,析构反序。 © 允许规范转载 打赏 赞赏作者 赞 1 如果觉得我的文章对你有用,请随意赞赏