I ran into a weird error today which I don't really understand:
Exception thrown: read access violation. this was nullptr.
In order to check if the error literally meant that 'this' was nullptr, i added a line above the crashing line which assigned this to a pointer. I added a breakpoint to the line to check, and on the 4th call to the function the variable was null, so clearly 'this' was null.

Which doesn't make any sense to me. How can a member function be called on an instance that doesn't exist?

Here's the function declaration/definition:
Qt Code:
  1. template<class T>
  2. T* GetComponent()
  3. {
  4. static_assert(std::is_base_of<Component, T>::value, "Type parameter 'T' does not derive from Component.");
  6. Entity* th = this; // This variable is null on 4th call.
  7. for (int i = 0; i < m_components.size(); i++) // And so is m_components, so it crashes here.
  8. {
  9. if (typeid(*m_components[i]).hash_code() == typeid(T).hash_code())
  10. {
  11. return dynamic_cast<T*>(m_components[i]);
  12. }
  13. }
  15. XENO_LOG_WARNING("Tried to get a component which doesn't exist on entity.");
  16. return nullptr;
  17. }
To copy to clipboard, switch view to plain text mode