C++ 标准库速览:cout、bind、mutex 与 lock_guard
std::cout 详解
std::cout 是 std::ostream 类型的全局实例,负责把数据送到标准输出。使用时需包含 <iostream>。
基础示例
#include <iostream>
int main() {
std::cout << "你好,世界" << '\n';
}
多类型输出
int age = 25;
double pi = 3.1415926;
char flag = 'Y';
std::string name = "Alice";
std::cout << "姓名:" << name
<< " 年龄:" << age
<< " π:" << pi
<< " 标志:" << flag << '\n';
格式化控制
#include <iomanip>
int value = 255;
double rate = 88.756;
// 宽度与填充
std::cout << std::setw(8) << std::setfill('0') << value << '\n'; // 00000255
// 保留两位小数
std::cout << std::fixed << std::setprecision(2) << rate << '\n'; // 88.76
// 十六进制与布尔文本
std::cout << std::hex << value << '\n'; // ff
std::cout << std::boolalpha << true << '\n'; // true
刷新机制
std::endl 会插入换行并立刻刷新缓冲区;std::flush 只刷新不换行;'\n' 仅插入换行,是否刷新取决于系统。
std::bind 用法
std::bind 将可调用对象与参数预先绑定,返回 std::function,便于延迟调用或适配接口。
绑定自由函数
#include <iostream>
#include <functional>
void log(int level, const std::string& msg) {
std::cout << "[" << level << "] " << msg << '\n';
}
int main() {
auto info = std::bind(log, 1, std::placeholders::_1);
info("system started"); // [1] system started
}
绑定成员函数
class Counter {
public:
void add(int a, int b) { std::cout << a + b << '\n'; }
};
Counter c;
auto fn = std::bind(&Counter::add, &c, 100, std::placeholders::_1);
fn(5); // 105
std::mutex 与线程安全
std::mutex 提供排他锁,保护共享数据。
手工加锁示例
#include <iostream>
#include <thread>
#include <mutex>
std::mutex g_mtx;
int g_count = 0;
void worker() {
for (int i = 0; i < 100000; ++i) {
g_mtx.lock();
++g_count;
g_mtx.unlock();
}
}
int main() {
std::thread t1(worker), t2(worker);
t1.join(); t2.join();
std::cout << g_count << '\n'; // 200000
}
RAII 管理:std::lock_guard
std::lock_guard 在构造时加锁、析构时解锁,避免忘记 unlock。
void safe_increment() {
std::lock_guard<std::mutex> lk(g_mtx);
++g_count;
} // 自动解锁
std::function 概览
std::function 是可调用对象的通用封装,支持函数、lambda、bind 结果等,实现类型擦除。
#include <functional>
std::function<int(int,int)> op;
op = [](int x, int y){ return x + y; };
std::cout << op(3,4) << '\n'; // 7
op = std::bind([](int x, int y, int z){ return x*y + z; },
std::placeholders::_1, 10, std::placeholders::_2);
std::cout << op(2,5) << '\n'; // 25