共享指针的问题 [英] problems with shared pointers

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

问题描述

您好,我是论坛新手,这是我的第一个问题,但最近我遇到了一些奇怪的行为.

我有两个班Goo和Foo.我在Foo中有一个方法,该方法返回Goo类型的共享指针.一切都可以编译...但是当我调试它时,我看到创建了2个类型为Goo的对象,并且Foo中的成员类从未得到值.

这是代码:

Hello I''n new on the forum, meaning It''s my first question asked but I recently came across some strange behavior.

I have two classes Goo and Foo. I have a method in Foo that returns a shared pointer of type Goo. It all compiles ok...but when I debug it I can see that 2 objects are created of type Goo and the member class inside Foo never gets a value.

here''s the code :

#include <memory>
#include <iostream>
#include <vector>
using namespace std;

class Goo
{
	int y;
public:
	Goo(){}
	~Goo(){}
	void set_y(int new_val) 
	{
		y=new_val;
	}

};

class Foo
{
	
	int x;
	//shared_ptr<Goo> gooptr;
	Goo Goomem;

	public:

	Foo(int val=0) :x(val) {}
	~Foo(){cout<<"desctructed";}
	
	void do_something() 
	{
		cout<<"doing nothing..."<<endl;
	}
	void set_x(int new_val) 
	{
		x=new_val;
	}
	void show_x() const {cout<< x<<endl; }
	shared_ptr<Goo> getshared()
	{
		shared_ptr<Goo> gooptr = make_shared<Goo>(Goomem);
		return gooptr;
	}

};


int main()
{
	bool expired=false;
	shared_ptr<Foo> pf (new Foo); 

	shared_ptr<Goo>gp=(*pf).getshared();
	(*gp).set_y(1);
	gp=(*pf).getshared();
	(*gp).set_y(2);
	gp=(*pf).getshared();
	(*gp).set_y(3);
	gp=(*pf).getshared();
	(*gp).set_y(4);
	gp=(*pf).getshared();

	pf.reset();

	return 0;
}



我肯定缺少某些东西...我的意思是我认为make_shared实际上每次都会创建一个新实例,并且由于没有其他指向该实例的智能指针,因为我重新分配了goo指针,所以它得到了收集的垃圾?我不知道...(很抱歉,这对您来说很明显,但是我才刚开始了解它们和C语言).



There must be something I''m missing...I mean I think that make_shared actually creates a new instance every time and since there are no more smart pointers that point to it, since i''m reassigning the goo pointer, it get''s garbage collected ? I don''t know...(Sorry if it''s obvious for you but I just started to learn about them and C in general)

推荐答案

方法:
shared_ptr<goo> getshared()
{
	shared_ptr<goo> gooptr = make_shared<goo>(Goomem);
        return gooptr;
}</goo></goo></goo>


每次调用Goo都会重新创建它的一个新实例,并且旧实例会被垃圾回收,因为不再引用它了.
这就是我实际上在Goo中写值的方式


reates a new instance of Goo each time it is called and the old instance get''s garbage colected because the are no more references to it.
this is how I actually wrote the value inside Goo

(*pf).setgoo((*gp).get_y());


如果你问我的话很漂亮的意大利面条. 感谢所有人


pretty spaghetti if you ask me...but it worked
thanks to all


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

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