Search code examples
c++openglglm-math

Weird crash at asigning a glm::vec3 constant reference to another glm::vec3


I'm having a ModelMatrix class in which i have a glm::vec3 defined as

glm::vec3 *position = nullptr;

Then i got a setter method

void ModelMatrix::SetPosition(const glm::vec3 &position)
{
    delete this->position;

    *this->position = position;
}

at asigning the constant reference the problem occurs.

It goes inside this method

template <typename T, precision P>
GLM_FUNC_QUALIFIER tvec3<T, P>& tvec3<T, P>::operator= (tvec3<T, P> const & v)
{
    this->x = v.x;
    this->y = v.y;
    this->z = v.z;
    return *this;
}

And then just crashes on the first line of the method.

This is a snippet from the call stack.

glm::detail::tvec3<float, (glm::precision)0>::operator= at type_vec3.inl:189 0x404f78   
core3d::ModelMatrix::SetPosition() at ModelMatrix.cpp:58 0x405bc3   
core3d::ModelMatrix::ModelMatrix() at ModelMatrix.cpp:7 0x40582b    

I don't have any error message. What is causing this error?


Solution

  • The much better approach here is to not use a pointer at all. glm::vec3 is a fixed size type that probably uses 12 or 16 bytes. I see absolutely no need to use a separate dynamic allocation for it.

    So where you currently declare your class member as:

    glm::vec3 *position;
    

    simply change this to:

    glm::vec3 position;
    

    Then remove all the new/delete calls you currently have for the class member. The setter method then becomes:

    void ModelMatrix::SetPosition(const glm::vec3 &position)
    {
        this->position = position;
    }