简体   繁体   中英

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?

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

This is because you are deferencing memory which you've now deallocated:

delete this->position;
*this->position = position;

I don't know why you are bothering to delete it, as I don't think the glm::vec3 destructor actually does anything important, so you can just do:

*this->position = position;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM