【问题标题】:Can't return std::shared_ptr from a function无法从函数返回 std::shared_ptr
【发布时间】:2018-02-03 01:01:11
【问题描述】:

我在从函数返回共享指针时遇到问题。在函数的 return 语句所在的行抛出异常。

函数如下:

// Icp.cpp
std::shared_ptr<ICPResult> Icp::fit() {

    // inner part of function

    // return values from inner part of fucntion
    double fitnessScore = icp.getFitnessScore();
    Eigen::Matrix4f transformation = icp.getFinalTransformation();

    return std::make_shared<ICPResult>(fitnessScore, transformation);
}

header header的相关部分:

// Icp.h
std::shared_ptr<models::detection::ICPResult> fit();

返回的类:

// ICPResult.h
class ICPResult : public DetectionResult {
    public:
        ICPResult();
        ICPResult(const double score, const Eigen::Matrix4f transformation);

        Eigen::Matrix4f transformationIcp;
    private:
};

父类:

// DetectionResult.h
class DetectionResult {
    public:
        DetectionResult();
        DetectionResult(const double score);

        double score;

    private:
};

在 if 语句所在行的“...VS17\VC\Tools\MSVC\14.12.25827\include\memory”的第 892 行抛出异常

void _Decref()
    {   // decrement use count
    if (_MT_DECR(_Uses) == 0)
        {   // destroy managed resource, decrement weak reference count
        _Destroy();
        _Decwref();
        }
    }

异常的文本: System.AccessViolationException: '试图读取或写入受保护的内存。这通常表明其他内存已损坏。'

我通常返回共享指针没有任何问题,但在这种情况下我不知道是什么问题。在我看来,对共享指针的引用计数存在一些问题,但我不知道如何处理它。如果您有任何解决此问题的想法,我将不胜感激。

【问题讨论】:

  • 请不要将文字作为图片发布。
  • 对不起,这是我的第一篇文章。已编辑
  • 这……很奇怪,目前尚不清楚这是错误的确切原因。能不能把它简化为一个最小的完整示例(关注最小),以便大家可以尝试运行它并检查。
  • 以您使用它的方式返回 shared_ptr 应该没问题。我认为那里没有普遍问题。也许 Eigen::Matrix4f 对象创建/删除不正确?您传递的 Matrix 调用复制构造函数(不作为引用传递),我假设您在将 Matrix 存储在成员变量中时正在调用另一个复制构造函数。
  • @FlorianM。看来你是对的。当我尝试在没有 Eigen:Matrix4f 的情况下返回共享指针时,一切正常。所以Matrix的传递存在一些问题。

标签: c++ c++11 shared-ptr


【解决方案1】:

好的,这就是解决方案。参考@Paul B 的回答,问题是每个包含 Eigen 数据类型的类或结构都必须处理固定大小的可矢量化 Eigen 类型。有关此问题的更多信息,请访问https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html

针对我的具体问题的解决方案是将 EIGEN_MAKE_ALIGNED_OPERATOR_NEW 宏添加到 ICPResult.h 的公共部分

// ICPResult.h
class ICPResult : public DetectionResult {
    public:
        ICPResult();
        ICPResult(const double score, const Eigen::Matrix4f transformation);

        Eigen::Matrix4f transformationIcp;
        EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    private:
};

非常感谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多