Search code examples
c++c++11shared-ptr

Can't return std::shared_ptr from a function


i have a problem with returning of the shared pointer from a function. Exception is thrown on the line with the return statement from the function.

Here is the function:

// 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);
}

Relevant part of header header:

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

Returned class:

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

        Eigen::Matrix4f transformationIcp;
    private:
};

Parent class:

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

        double score;

    private:
};

Exception was thrown at line 892 in "...VS17\VC\Tools\MSVC\14.12.25827\include\memory" at the line with if statement

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

Text of the exception: System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

I usually return shared pointer without any problems, but in this case i have no idea what is the problem. It seems to me like some problem with counting of references to the shared pointer, but i dont know how to handle it. I will be grateful for any ideas how to solve this problem.


Solution

  • Ok here is the solution. With reference to @Paul B answer the problem was that every class or structure which contain Eigen data types have to handle with fixed-size vectorizable Eigen types. For more info about this problem please visit https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html

    Solution for my specific problem is adding EIGEN_MAKE_ALIGNED_OPERATOR_NEW macro to public part of the 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:
    };
    

    Many thanks