[英]error related to binding non-const lvalue to rvalue in constructor
For the following template definitions in my header file, 对于我的头文件中的以下模板定义,
template<typename T>
class node{
private:
T& data;
shared_ptr<node<T>>& next;
public:
node(T&);
~node();
};
template<typename X>
class list{
private:
shared_ptr<X>& head;
public:
list();
~list();
};
and the following line of code in main()
: 以及main()
的以下代码行:
list<node<string>>menu;
I get the following compilation error for the member initialization of shared_ptr<X>& head
inside the constructor: 对于shared_ptr<X>& head
构造函数内部的成员初始化,我得到以下编译错误:
template<typename X>
list<X>::list():head(make_shared<X>(NULL)){
}
error: cannot bind non-const lvalue reference of type "std::shared_ptr<node<std::basic_string<char> > >" to an rvalue of type "std::shared_ptr<node<std::basic_string<char> > >"
list<X>::list():head(make_shared<X>(NULL)){
^
My understanding is that the error stems from trying to bind the rvalue generated by call to make_shared()
to lvalue shared_ptr<X>& head
. 我的理解是,该错误源自尝试将对make_shared()
的调用生成的右值绑定到左值shared_ptr<X>& head
。
How can I resolve this error? 如何解决此错误?
The problem is the following, you are creating a temporary 问题是以下,您正在创建一个临时
make_shared<X>(NULL)
that will die after the line is executed, and the reference in your class will be dangling (ie referencing something that has been destroyed), if you try to access the reference you will be in undefined behavior territory (your program can crash, or worse continue in a corrupted state). 该行将在执行后消失,并且您的类中的引用将悬空(即引用已被破坏的对象),如果尝试访问该引用,您将处在未定义的行为范围内(您的程序可能崩溃,或更糟糕的是,继续处于损坏状态)。 A way to fix it would be to not use references to shared_ptr
but directly shared_ptr
in all your classes which is way safer. 解决该问题的一种方法是不使用对shared_ptr
引用,而是在所有类中直接使用shared_ptr
,这是更安全的方法。
Secondly, you might want to use nullptr
instead of NULL
其次,您可能要使用nullptr
而不是NULL
Lastly, I think you are misunderstanding what the references are supposed to do: they are not about ownership of a resource, but simply allow access to a resource, when you have a reference to something you must be sure that somebody else is keeping that resource alive for as long as you want to access the resource via the reference (there is an exception: lifetime extension via a local const ref, see https://blog.galowicz.de/2016/03/23/const_reference_to_temporary_object/ ). 最后,我认为您误解了引用应做的事情:它们与资源所有权无关,而只是允许访问资源,当您引用某项内容时,必须确保其他人保留了该资源只要您想通过引用访问资源即可生存(有一个例外:通过本地const ref延长生命周期,请参阅https://blog.galowicz.de/2016/03/23/const_reference_to_temporary_object/ )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.