shared_ptr空指针和赋值 [英] shared_ptr null pointer and assignment

查看:6756
本文介绍了shared_ptr空指针和赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用shared_ptr就像我使用一个实际的指针。我想要能够做像

I want to use shared_ptr just like I'd use an actual pointer. I wanted to be able to do things like

shared_ptr<int> a;
a = new int(5);
a = 0;
shared_ptr<int> foo()
    return 0;

但默认情况下不会实现。

but it is not implemented by default.

我通过添加

template<class Y> void operator=( int i )
{
    reset(i);
}
template<class Y> void reset(int i)
{
    this_type(i).swap(*this);
}
template<class Y> void operator=( Y * p )
{
    reset(p);
}
shared_ptr(int i): px(0), pn()
{
}

唯一的事情是,如果我做a = -1;它会编译并给我一个空指针,这不应该是一个问题,因为通常你不能分配一个整数值指针。

The only thing is that if I do a = -1; it will compile and give me a null pointer, which shouldn't be a problem because normally you can't assign an integer value to a pointer.

所以我的问题是,这是一个正确的方式来实现这个或者我忘了可能会崩溃的应用程序的情况?因为在我看来,我看到的一个nullpointer为一个shared_ptr唯一的方法是调用默认的构造函数,在代码中不是很优雅:ptr = 0;。

So my question is, is this a correct way to implement this or have I forgot cases that might crash the application? Because everywhere I looked, the only way I saw to get a nullpointer for a shared_ptr was to call the default constructor which isn't very elegant in code compared to: ptr = 0;.

推荐答案

否。 不要更改源代码。这是因为一个原因,很聪明的人已经决定,它的定义方式比任何你要编辑的更好。

No. Do not change the source. It's like that for a reason and very smart people have decided that the way it's defined is better than whatever you're going to edit it to be.

你有什么没有意义。你不能将一个整数赋值给一个指针,它们是两种不同的类型,但你已经给它一个语义。你说:...这不应该是一个问题,因为通常你不能分配一个整数值到一个指针,但你也说在你的问题的顶部我想使用shared_ptr就像我使用实际指针。好吧,是吗?因为将整数指定为指针以将它们设置为null,离实际指针的距离远远远远大于你可以得到的指针。

What you have doesn't even make sense. You cannot assign an integer to a pointer, they are two different types, yet you've given it such semantics. You say: "...which shouldn't be a problem because normally you can't assign an integer value to a pointer", but you also said at the top of your question "I want to use shared_ptr just like I'd use an actual pointer". Well, which is it? Because assigning integers to pointers to set them to null is about as far from an actual pointer as you can get.

你需要退一步,实现你想要的并不总是最好的事情。您应该还原这些更改并正确使用类。我不想是平均值,但这是严重不是你想去的路线;它是危险的,有无意义的语义,并且都是无法维护的。

You need to take a step back and realize what you want isn't always the best thing to do. You should revert those changes and use the class properly. I don't want to be mean but this is seriously not the route you want to go; it's dangerous, has nonsensical semantics, and is all around unmaintainable.

这篇关于shared_ptr空指针和赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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