将 auto_ptr 分配给 weak_ptr
Assign auto_ptr to weak_ptr
我仍在探索 C++ 11。所以我很确定我做错了什么。但是我就是想不通问题所在。
我有以下代码:
MyClass::MyClass(const PlayerEventListener* eventListener)
{
weak_ptr<PlayerEventListener> _listener;
std::auto_ptr<PlayerEventListener> autoPtr;
autoPtr.reset(const_cast<PlayerEventListener*> (eventListener));
// I get error for this line
_listener = autoPtr;
}
我收到以下错误:没有可行的重载'='
但是下面的代码可以正常编译:
MyClass::MyClass(const PlayerEventListener* eventListener)
{
weak_ptr<PlayerEventListener> _listener;
std::shared_ptr<PlayerEventListener> sharedPtr;
sharedPtr.reset(const_cast<PlayerEventListener*> (eventListener));
// I get error for this line
_listener = sharedPtr;
}
有人可以解释为什么我不能将自动指针转换为弱指针吗?
weak_ptr
is an object that holds a safe reference to an object actually held by shared_ptr
, not auto_ptr
. Therefore, there is no any overloaded operator=
that could provide assigning auto_ptr
to weak_ptr
in the implementation of weak_ptr
. It can be verified by compiling this example code 并查看错误
In constructor 'MyClass::MyClass(const PlayerEventListener*)':
21:14: error: no match for 'operator=' (operand types are 'std::weak_ptr<PlayerEventListener>' and 'std::auto_ptr<PlayerEventListener>')
记住: 根据http://www.cplusplus.com/reference/memory/auto_ptr/:
This class template (auto_ptr
) is deprecated as of C++11. unique_ptr
is a new
facility with a similar functionality, but with improved security (no
fake copy assignments), added features (deleters) and support for
arrays. See unique_ptr
for additional information.
我仍在探索 C++ 11。所以我很确定我做错了什么。但是我就是想不通问题所在。
我有以下代码:
MyClass::MyClass(const PlayerEventListener* eventListener)
{
weak_ptr<PlayerEventListener> _listener;
std::auto_ptr<PlayerEventListener> autoPtr;
autoPtr.reset(const_cast<PlayerEventListener*> (eventListener));
// I get error for this line
_listener = autoPtr;
}
我收到以下错误:没有可行的重载'='
但是下面的代码可以正常编译:
MyClass::MyClass(const PlayerEventListener* eventListener)
{
weak_ptr<PlayerEventListener> _listener;
std::shared_ptr<PlayerEventListener> sharedPtr;
sharedPtr.reset(const_cast<PlayerEventListener*> (eventListener));
// I get error for this line
_listener = sharedPtr;
}
有人可以解释为什么我不能将自动指针转换为弱指针吗?
weak_ptr
is an object that holds a safe reference to an object actually held by shared_ptr
, not auto_ptr
. Therefore, there is no any overloaded operator=
that could provide assigning auto_ptr
to weak_ptr
in the implementation of weak_ptr
. It can be verified by compiling this example code 并查看错误
In constructor 'MyClass::MyClass(const PlayerEventListener*)':
21:14: error: no match for 'operator=' (operand types are 'std::weak_ptr<PlayerEventListener>' and 'std::auto_ptr<PlayerEventListener>')
记住: 根据http://www.cplusplus.com/reference/memory/auto_ptr/:
This class template (
auto_ptr
) is deprecated as of C++11.unique_ptr
is a new facility with a similar functionality, but with improved security (no fake copy assignments), added features (deleters) and support for arrays. Seeunique_ptr
for additional information.