如何将std::function放入std::unique_ptr智能指针并使用?已尝试未成功
将std::function放入std::unique_ptr的正确用法
你的代码存在两个核心问题,直接导致无法正常运行:
1. 智能指针调用方式错误
std::unique_ptr是指针封装类型,不能直接像普通函数对象那样调用。必须先访问其内部持有的std::function对象,再调用函数运算符。
2. Lambda捕获与逻辑混淆
你捕获了外部的section变量,但lambda参数是_section,却在内部访问section.GetIntegers(),这会导致始终操作外部传入的初始section,而非参数传入的对象,逻辑不符合预期。
修正后的代码如下:
const inline void PrintSection(TurboINI::types::section §ion) { std::cout << "[\"" << section.GetKey() << "\"]\n"; auto PrintSectionContent = std::make_unique<std::function<void(TurboINI::types::section &)>>( [](TurboINI::types::section &_section) { // 无需捕获外部section,直接使用参数 if (!_section.GetIntegers().empty()) { for (const auto &i : _section.GetIntegers()) { std::cout << '\t'; PrintInteger(i); } } if (!_section.GetStrings().empty()) { for (const auto &i : _section.GetStrings()) { std::cout << '\t'; PrintString(i); } } }); // 两种正确调用方式二选一 (*PrintSectionContent)(section); // PrintSectionContent->operator()(section); }
关键说明:
- 智能指针调用:可以通过解引用指针(
*PrintSectionContent)得到std::function对象后调用,或者直接用->operator()触发函数调用。 - Lambda捕获优化:因为逻辑是操作参数传入的对象,所以无需捕获外部变量,避免了引用悬空的风险。如果确实需要捕获外部变量,务必保证变量生命周期长于lambda的使用周期。
另外补充:如果没有动态分配的特殊需求,直接使用std::function对象会比用unique_ptr包裹更简洁。
内容的提问来源于stack exchange,提问作者Александр Алибеков
相关产品推荐
相关产品推荐

