我需要为一项工作构建一个小型OpenGL包装器。我试图避免为所有我的类编写复制构造函数和赋值函数。
最懒惰且不写复制的方法是使用指针,但由于指针是邪恶的,我尝试仅使用std :: shared_ptr。
问题在于,通过使用通过值接收std :: shared_ptr的构造函数,我的程序会崩溃,并且当使用完美转发时,仅在传递左值时才起作用。
最懒惰且不写复制的方法是使用指针,但由于指针是邪恶的,我尝试仅使用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;
(...)
我尝试了两种不同的构造函数:
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::move中的左值引用或右值引用都不可行。当调用std::shared_ptr构造函数(在程序构造函数内部)时,程序会挂起。
我看了Scott Mayers的通用引用讲座,觉得自己理解了,结果还是出了这个问题。
'assert'
的想法能够有所帮助。另外,我通常会将成员名称设置为唯一的,比如_dep1(dep1)
或_dep1(arg1)
。 - sehe