为什么我不能转换nullptr到weak_ptr<> [英] why i can't cast nullptr to weak_ptr<>

查看:713
本文介绍了为什么我不能转换nullptr到weak_ptr<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class MyClass {
public:
     MyClass(std::weak_ptr<MyClass> parent){}
}

我想这样做:

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

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

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

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));

为什么?

推荐答案

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

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 std :: weak_ptr< MyClass>()), c $ c> nullptr :

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

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

这篇关于为什么我不能转换nullptr到weak_ptr&lt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆