为什么我不能将nullptr转换为weak_ptr

时间:2021-07-12 21:13:50
class MyClass {
public:
     MyClass(std::weak_ptr<MyClass> parent){}
}

i want to do this:

我想做这个:

auto newInstance = std::make_shared<MyClass>(nullptr);

or default value of weak_ptr argument is null, such as :

或者weak_ptr参数的默认值为null,例如:

void function(int arg,std::weak_ptr<MyClass> obj = nullptr);

but, what i need is to do this instead:

但是,我需要的是这样做:

auto newInstance = std::make_shared<MyClass>(std::shared_ptr<MyClass>(nullptr));

why is that?

这是为什么?

2 个解决方案

#1


24  

Because a weak_ptr in concept can only be constructed from another weak_ptr or shared_ptr. It just doesn't make sense to construct from a raw pointer, whether it's nullptr or not.

因为概念中的weak_ptr只能从另一个weak_ptr或shared_ptr构造。从原始指针构造它是没有意义的,无论它是否为nullptr。

You can use a default constructed weak_ptr (std::weak_ptr<MyClass>()) where you are trying to use nullptr:

您可以使用默认构造的weak_ptr(std :: weak_ptr ())来尝试使用nullptr:

auto newInstance = std::make_shared<MyClass>(std::weak_ptr<MyClass>());
void function(int arg,std::weak_ptr<MyClass> obj = std::weak_ptr<MyClass>());

#2


-1  

A weak pointer's primary purpose is usually to know whether an object that might be destroyed by other code still exists. How could a weak pointer constructed from an ordinary pointer possibly know whether the object still exists? Can you even imagine a way this could possibly work?

弱指针的主要目的通常是知道可能被其他代码销毁的对象是否仍然存在。从普通指针构造的弱指针怎么可能知道对象是否仍然存在?你能想象出一种可能有用的方式吗?

#1


24  

Because a weak_ptr in concept can only be constructed from another weak_ptr or shared_ptr. It just doesn't make sense to construct from a raw pointer, whether it's nullptr or not.

因为概念中的weak_ptr只能从另一个weak_ptr或shared_ptr构造。从原始指针构造它是没有意义的,无论它是否为nullptr。

You can use a default constructed weak_ptr (std::weak_ptr<MyClass>()) where you are trying to use nullptr:

您可以使用默认构造的weak_ptr(std :: weak_ptr ())来尝试使用nullptr:

auto newInstance = std::make_shared<MyClass>(std::weak_ptr<MyClass>());
void function(int arg,std::weak_ptr<MyClass> obj = std::weak_ptr<MyClass>());

#2


-1  

A weak pointer's primary purpose is usually to know whether an object that might be destroyed by other code still exists. How could a weak pointer constructed from an ordinary pointer possibly know whether the object still exists? Can you even imagine a way this could possibly work?

弱指针的主要目的通常是知道可能被其他代码销毁的对象是否仍然存在。从普通指针构造的弱指针怎么可能知道对象是否仍然存在?你能想象出一种可能有用的方式吗?