目录
读写锁std::shared_timed_mutex和std::shared_lock
可以对捕获列表的捕获变量“赋值”,C++14中的这个新特性允许了在捕获列表中定义前面没有出现过的变量,但必须赋予一个值,并且不使用类型说明符和auto,类型由编译器自动推断。
#include#include using namespace std; int main() { int a = 2; [a = sin(a)]() { cout << a << endl; // 0.909297 cout << cos(a) << endl; // 0.6143 }(); cout << a << endl; // 2 cout << cos(a) << endl; // -0.416147 return 0; }
C++14中增加了[[deprecated]]标记,可以修饰类、函数、变量等,当程序中使用了被其修饰的模块时,编译器会产生告警,提示用户该标记标记的内容将来可能会被废弃,尽量不要使用。
struct [[deprecated]] Tmp {};
C++14中通过std::shared_timed_mutex和std::shared_lock实现读写锁,保证多个线程可以同时读,但是写线程必须独立运行,写操作不能和读操作同时进行。
struct ThreadSafe {
mutable std::shared_timed_mutex _mutex;
int _value;
ThreadSafe() { _value = 0; }
int get() const {
std::shared_lock loc(_mutex);
return _value;
}
void increase() {
std::unique_lock lock(_mutex);
_value += 1;
}
};
类模板 std::integer_sequence 表示一个编译时的整数序列。在用作函数模板的实参时,能推导参数包 Ints 并将它用于包展开。
#include#include #include #include template void print_sequence(std::integer_sequence int_seq) { std::cout << "The sequence of size " << int_seq.size() << ": "; ((std::cout << ints << ' '), ...); std::cout << '\n'; } // 转换数组为 tuple template auto a2t_impl(const Array &a, std::index_sequence ) { return std::make_tuple(a[I]...); } template > auto a2t(const std::array &a) { return a2t_impl(a, Indices{}); } // 漂亮地打印 tuple template void print_tuple_impl(std::basic_ostream &os, const Tuple &t, std::index_sequence ) { ((os << (Is == 0 ? "" : ", ") << std::get (t)), ...); } template auto &operator<<(std::basic_ostream &os, const std::tuple &t) { os << "("; print_tuple_impl(os, t, std::index_sequence_for {}); return os << ")"; } int main() { print_sequence(std::integer_sequence {}); print_sequence(std::make_integer_sequence {}); print_sequence(std::make_index_sequence<10>{}); print_sequence(std::index_sequence_for {}); std::array array = {1, 2, 3, 4}; // 转换 array 为 tuple auto tuple = a2t(array); static_assert(std::is_same >::value, ""); // 打印到 cout std::cout << tuple << '\n'; }
相对于swap不对后者赋值
#include#include #include using namespace std; int main() { vector vec1{1, 2, 3, 4}; vector vec2{5, 6, 7, 8}; cout << "exchange before: " << endl; cout << "vec1: " << endl; copy(vec1.begin(), vec1.end(), ostream_iterator {cout, " "}); cout << endl << "vec2: " << endl; copy(vec2.begin(), vec2.end(), ostream_iterator {cout, " "}); exchange(vec1, vec2); cout << endl << "exchange after: " << endl; cout << "vec1: " << endl; copy(vec1.begin(), vec1.end(), ostream_iterator {cout, " "}); cout << endl << "vec2: " << endl; copy(vec2.begin(), vec2.end(), ostream_iterator {cout, " "}); return 0; }
#include#include #include int main() { std::string str{"hello world"}; std::cout << str << std::endl; // hello world std::cout << std::quoted(str) << std::endl; // "hello world" return 0; }