如何将所有权从共享指针向量转移到另一个指针?

时间:2019-06-16 15:49:10

标签: c++ shared-ptr smart-pointers

我试图了解C ++中传递数据的最佳方法是什么。在下面的示例中,我尝试将数据的所有权(Shader)传递给类(ShaderProgram)。

我可以使用原始指针来做到这一点,但这增加了管理它不希望做的生命周期的需求。不幸的是,当我尝试移动共享指针的方法内部时,得到了read access violation

std::shared_ptr<ShaderProgram> modelShaders; // this is inside another class, but I guess it's not too important

int main() {
    std::shared_ptr<Shader> vert = std::make_shared<Shader>(Shader::VERTEX, std::string("res/shaders/model/basic.vert"));
    std::shared_ptr<Shader> frag = std::make_shared<Shader>(Shader::FRAGMENT, std::string("res/shaders/model/basic.frag"));

    std::vector<std::shared_ptr<Shader>> shaders;

    shaders.push_back(std::move(vert));
    shaders.push_back(std::move(frag));

    modelShaders->compileShaders( shaders );
}
    // std::vector<std::shared_ptr<Shader>> m_shaders; definition inside the class

void ShaderProgram::compileShaders(std::vector<std::shared_ptr<Shader>> &shaders)
{
    GLuint program = glCreateProgram();

    for (auto shaderIter = shaders.begin(); shaderIter != shaders.end(); shaderIter++)
    {
        std::shared_ptr shader = *shaderIter;

        GLuint shaderID = compileShader(shader);

        GL(glAttachShader(program, shaderID));

        shader->setID(shaderID);

        m_shaders.push_back(std::move(shader)); // here I get a read access violation
    }

我的目的是避免在不需要类的情况下创建/销毁类。我不希望Shader实例被破坏或复制。

PS:如果有人可以推荐一些有关传递数据的文章等,那太好了!

编辑

class ShaderProgram
{
private:
    std::vector<std::shared_ptr<Shader>> m_shaders;
public:
    ShaderProgram()
        : m_id(0) {};
    ~ShaderProgram() {
        std::cout << "[ShaderProgram] destroyed" << std::endl;
    };

    ...

    GLuint compileShader(const std::shared_ptr<Shader>& shader);
    void compileShaders(const std::vector<std::shared_ptr<Shader>> &shaders);

   ...
GLuint ShaderProgram::compileShader(const std::shared_ptr<Shader> &shader) {

    GLuint id = 0;
    std::string src = shader->getSource();

    const char* cSrc = src.c_str();

    GL((id = glCreateShader(shader->getGLType())));
    GL(glShaderSource(id, 1, &cSrc, NULL));
    GL(glCompileShader(id));

    if (GetStatus(id, Status::SHADER, GL_COMPILE_STATUS, shader->getName(), "COMPILATION FAILURE") != GL_TRUE)
    {
        return 0;
    }

    return id;
}

1 个答案:

答案 0 :(得分:0)

该问题与std::vector<std::shared_ptr<Shader>> m_shaders;尚未在构造函数中初始化有关。我承受着<vector>自动处理的压力,但事实并非如此。通过添加以下代码,一切按预期进行:

    ShaderProgram() : m_shaders(std::vector<std::shared_ptr<Shader>>()) {};