You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

std::unique_ptr swap调用失败,编译报错无匹配函数

解决std::unique_ptr::swap调用不匹配的问题

先来看你的代码:

#include <memory>
#include <vector>
struct Core{ Core(int n){} };
int main() {
 int base;
 std::vector<std::unique_ptr<Core>> cores;
 cores.push_back( std::move(std::unique_ptr<Core>(new Core(base))) );
 cores[0].swap(std::unique_ptr<Core>(new Core(base)));
 return 0;
}

编译时遇到的错误:

||=== Build: Release in Test (compiler: GNU GCC Compiler) ===|
在函数'int main()'中
错误:找不到匹配的函数调用'std::unique_ptr::swap(std::unique_ptr)'
提示:候选函数是:
提示:void std::unique_ptr<_Tp,_Dp>::swap(std::unique_ptr<_Tp,_Dp>&) [with_Tp = Core; _Dp = std::default_delete]
提示:无法将参数1从'std::unique_ptr'转换为'std::unique_ptr&'的内容

问题原因

std::unique_ptr的成员函数swap要求传入一个非const的左值引用(也就是有名字、可修改的对象),但你这里传入的std::unique_ptr<Core>(new Core(base))是临时创建的右值对象——C++规则里不允许把右值绑定到非const的左值引用上,所以编译器找不到匹配的函数重载,直接报错。

几种解决方案

1. 先创建命名的unique_ptr对象再swap

把临时对象变成有名字的左值,就能满足swap成员函数的参数要求:

std::unique_ptr<Core> new_core(new Core(base));
cores[0].swap(new_core);

2. 使用全局的std::swap函数

全局std::swap针对unique_ptr有特化实现,它可以借助移动语义处理右值对象:

std::swap(cores[0], std::unique_ptr<Core>(new Core(base)));

3. 直接用移动赋值(最简洁推荐)

其实你完全不需要用swap,unique_ptr本身支持移动赋值,直接赋值就能替换原有指针,还会自动释放旧对象的资源:

// 基础写法
cores[0] = std::unique_ptr<Core>(new Core(base));
// C++14及以上更安全的写法(推荐,避免潜在内存泄漏)
cores[0] = std::make_unique<Core>(base);

内容的提问来源于stack exchange,提问作者Sheed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:19:04