3

我必须为一项工作构建一个小型 OpenGL 包装器。我试图避免为我的所有类编写复制构造函数和复制赋值。

真正懒惰且从不写副本的一种方法是使用指针,但由于指针是邪恶的,我试图独占使用std::shared_ptr.

问题是通过使用一个std::shared_ptr按值接收的构造函数,我的程序崩溃了,并且当使用完美转发时,它仅在我传递左值时才有效。

// this class doesn't have any default, copy constructors.
class Dep
{
    Dep(std::string path, GLenum type);
};

class Program
{
std::shared_ptr<Dep> dep1;
std::shared_ptr<Dep> dep2;

(...)

我尝试了 2 种不同的构造函数:

template <class T, class = typename std::enable_if<std::is_constructible<std::shared_ptr<Dep>, T>::value>::type>
Program(T&& dep1, T&& dep2)
: dep1(std::forward<T>(dep1)), dep2(std::forward<T>(dep2))
{
}

和另一个

Program(std::shared_ptr<Dep> dep1, std::shared_ptr<Dep> dep2)
: dep1(std::move(dep1)), dep2(std::move(dep2))
{
}

我想要做的是能够传递左值或右值共享指针,但它不起作用,除非我在前向指针上使用左值,否则每次都会崩溃。

// passing these work on the std::forward one, but that's the only case it works
// if i try to use std::make_shared as parameter (for rvalue) it crashes on both
// the std::move and std::forward ones.
auto vs = std::make_shared<GLShader>("TriangleVS.glsl", GL_VERTEX_SHADER);
auto fs = std::make_shared<GLShader>("TriangleFS.glsl", GL_FRAGMENT_SHADER);

摘要: std::forward 上的左值有效。std::forward 上的右值不起作用。std::move one 上的左值或右值不起作用。它只是在调用 std::shared_ptr 构造函数时(在 Program 构造函数内)挂起程序。

我看了 Scott Mayers 的通用参考谈话,我以为我理解了这一点,这发生在我身上。

4

1 回答 1

1

I don't see anything wrong with this code, and it tests out OK on http://ideone.com/jlShgB too:

#include <memory>
#include <utility>
#include <string>
#include <cassert>

enum GLenum { foo };

// this class doesn't have any default, copy constructors.
struct Dep
{
    Dep(std::string path, GLenum type) {}
    Dep() = delete;
    Dep(Dep const&) = delete;
};

struct Program
{
    std::shared_ptr<Dep> dep1;
    std::shared_ptr<Dep> dep2;

#if 1
    template <class T, class = typename std::enable_if<std::is_constructible<std::shared_ptr<Dep>, T>::value>::type>
    Program(T&& dep1, T&& dep2)
        : dep1(std::forward<T>(dep1)), dep2(std::forward<T>(dep2))
    {
    }
#else
    Program(std::shared_ptr<Dep> dep1, std::shared_ptr<Dep> dep2)
        : dep1(std::move(dep1)), dep2(std::move(dep2))
    {
    }
#endif
};

int main()
{
    auto dep1 = std::make_shared<Dep>("dep1", foo);
    auto dep2 = std::make_shared<Dep>("dep2", foo);
    Program p(std::move(dep1), std::move(dep2));

    assert(!dep1 && !dep2);
}

Of course if you change #if 1 to #if 0, the assert will raise an exception because the dep1/dep2 will not have been moved from.

This leads me to suspect another issue somewhere else. If you can isolate a SSCCE that exhibits the problem, please let me know.

于 2012-11-14T21:21:18.710 回答