【问题标题】:Why do I get SIGSEGV error when use class function from pointer?为什么从指针使用类函数时会出现 SIGSEGV 错误?
【发布时间】:2013-08-22 05:05:43
【问题描述】:

我是 C++ 新手,遇到了第一个麻烦。我有一个 GameObject 类,我必须以某种方式存储许多组件。每个组件都是一个不同的类,所以我不能正常使用向量。我决定存储组件的类型和指向该对象的指针。问题是,当我获取、返回该组件并使用使用它的成员变量的类函数时,我得到 SIGSEGV 错误(是的,听起来令人困惑)。但是,如果我通常使用该类和该函数,我不会收到 SIGSEGV 错误。

GameObject.h:

enum ComponentType
{
    MeshComponent // currently only one type
};

struct Component
{
    ComponentType type;
    void *pointer;
};
class GameObject
{
    private:
    std::vector<Component> components;
    public:
    void addComponent(ComponentType type);
    template<typename T> T* getComponent()
    {
        for(std::vector<Component>::size_type i = 0; i != components.size(); i++)
        {
            // will need to somehow check T type later
            if(components[i].type == MeshComponent)
            {
                return (Mesh*)&components[i].pointer;
            }
        }
        Debug::Loge(GAMEOBJECT_TAG, "No %s component in %s gameobject!", componentTypeToString(MeshComponent).c_str(), name.c_str());
        return 0;
    }
}

GameObject.cpp:

void GameObject::addComponent(ComponentType type)
{
    Component component;
    component.type = type;
    if(type == MeshComponent)
    {
        Mesh *mesh = new Mesh();
        component.pointer = &mesh;
    }
    components.push_back(component);
}

Mesh.h

class Mesh
{
    public:
    Mesh *setMeshData(std::vector<GLfloat> data);
};

Mesh.cpp

Mesh *Mesh::setMeshData(vector<GLfloat> data)
{
    meshData = data;
    return this;
}

最后我是这样使用它的:

GameObject object;
void somefunction()
{
    object.addComponent(MeshComponent);
    object.getComponent<Mesh>()->setMeshData(triangle_data); // SIGSEGV HERE!!
    // if I use this one instead above - no sigsegv, everything is fine.
    Mesh mesh;
    mesh.setMeshData(triangle_data);
}

【问题讨论】:

  • return (Mesh*)&amp;components[i].pointer; 快速浏览 - 看起来您正在获取所需的指针 (.pointer),然后获取 指针 的地址并返回。
  • 您至少应该检查object.getComponent&lt;Mesh&gt;() 不会返回0
  • 如果你有 C++11,一个 std::vector<:unique>> 可能会让生活更轻松

标签: c++ c++11 android-ndk void-pointers segmentation-fault


【解决方案1】:

在这里

    Mesh *mesh = new Mesh();
    component.pointer = &mesh;

您正在获取指向mesh 的指针地址。而是尝试

    Mesh *mesh = new Mesh();
    component.pointer = mesh;

因为您将Component-指针定义为void* pointer。如果您想获取Mesh* 的地址,则必须使用void** pointer,但这很愚蠢,并且会导致另一个SIGSEGV

【讨论】:

  • 还有return (Mesh*)&amp;components[i].pointer,这是同一种问题。
【解决方案2】:
if(components[i].type == MeshComponent)
{
     return (Mesh*)&components[i].pointer;
}

您的返回类型是 Mesh* 但&amp;components[i].pointer 将是 void**。 + @bas.d 的上述解释

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    相关资源
    最近更新 更多