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

如何修复C++中「use of deleted function ‘Ort::Value::Value(const Ort::Value&)’」错误

如何修复C++中「use of deleted function ‘Ort::Value::Value(const Ort::Value&)’」错误

嘿,这个错误我之前踩过坑,其实核心原因很直白:Ort::Value类的拷贝构造函数被显式删除了——也就是说你既不能直接拷贝它,也不能返回局部Ort::Value对象的引用(这还会引发悬空引用的问题)。

先看你代码里的问题:你的函数返回类型是const Ort::Value &,但函数内部要创建的是一个局部的Ort::Value对象,返回局部对象的引用会导致对象销毁后引用直接失效;就算你想拷贝返回,Ort::Value也不允许这么做,这就是报错的根源。

下面结合你的代码给具体修复步骤:

1. 修正函数返回类型

把返回类型从const Ort::Value &改成Ort::Value。C++11及以后支持移动语义,Ort::Value类肯定实现了移动构造函数,所以值返回不会触发拷贝,而是高效转移对象所有权,完全符合需求。

2. 完整创建并返回Ort::Value对象

你的代码里创建Ort::Value的部分没写完,我帮你补全逻辑,同时确保返回时利用移动语义(直接返回临时对象的话,编译器会自动优化成移动,不用手动写std::move)。

修改后的完整代码如下:

Ort::Value img_file_to_tensor(std::string input_img_path) {
    // Load the image using OpenCV
    cv::Mat input_mat = cv::imread(input_img_path);

    // Convert to float
    cv::cvtColor(input_mat, input_mat, cv::COLOR_BGR2RGB);
    input_mat.convertTo(input_mat, CV_32F);
    // Normalize
    input_mat /= 255.0;

    // Convert the preprocessed image to a vector of floats
    Ndarray<float> input_img = mat_to_ndarray(input_mat);
    input_img.transpose({2, 0, 1});
    input_img.expand_dims(0);

    auto input_vector = input_img.data;
    auto input_shape = input_img.shape;

    // 创建Ort的内存信息
    Ort::MemoryInfo memoryInfo = Ort::MemoryInfo::CreateCpu(
        OrtAllocatorType::OrtArenaAllocator, 
        OrtMemType::OrtMemTypeDefault
    );

    // 创建Tensor并返回,编译器会自动用移动构造处理
    return Ort::Value::CreateTensor<float>(
        memoryInfo,
        input_vector.data(),
        input_vector.size(),
        input_shape.data(),
        input_shape.size()
    );
}

3. 额外注意事项

  • 如果你在其他代码里有试图拷贝Ort::Value的操作(比如Ort::Value val = another_val;),要改成移动语义:Ort::Value val = std::move(another_val);,这样就不会触发被删除的拷贝构造函数。
  • 永远别返回局部对象的引用,这是C++里的经典坑,会导致未定义行为。

这样改完,那个删除函数的错误应该就彻底消失啦!

备注:内容来源于stack exchange,提问作者chikadance

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.17 08:14:51