简体   繁体   English

C ++使用智能指针

[英]C++ working with smart pointers

In my code, I have function prototype 在我的代码中,我有函数原型

void AddBenchNode(ref_ptr<Group> root ,ref_ptr<Node> benches, bool setAttitude = false, float scale_x =.15, float scale_y =15, float scale_z = 15, int position_x = 250, int position_y = 100, int position_z =0 );

where ref_ptr is a smart pointer. 其中ref_ptr是智能指针。

In my main function, I define 2 smartpointers of type ref_ptr and ref_ptr and pass them to a call to my function, AddBenchNode. 在我的主要函数中,我定义了ref_ptr和ref_ptr类型的2个智能指针,并将它们传递给对我的函数AddBenchNode的调用。

ref_ptr<Group> root = new Group();
ref_ptr<Node> benches = readNodeFile("Models/test.ive");
AddBenchNode(root, benches, true);

When the call executes, nothing happens. 当调用执行时,什么也没有发生。 As in no changes are made to the root pointer. 因为没有更改根指针。 What I want to know is if I am making this call correctly as I have it? 我想知道的是,我能否正确拨打此电话? Or do I have to re-define my function to take pointers to these smartpointers? 还是我必须重新定义函数以获取指向这些智能指针的指针?

Now I did try passing by reference 现在我确实尝试通过引用传递

void AddBenchNode(osg::ref_ptr<osg::Group>& root ,osg::ref_ptr<osg::Node>& benches, bool setAttitude = false, float scale_x =.15, float scale_y =15, float scale_z = 15, int position_x = 250, int position_y = 100, int position_z =0 );

That resulted in some linker errors. 这导致了一些链接器错误。

Error 2 error LNK2001: unresolved external symbol "void __cdecl AddBenchNode(class osg::ref_ptr &,class osg::ref_ptr &,bool,float,float,float,int,int,int)" (?AddBenchNode@@YAXAAV?$ref_ptr@VGroup@osg@@@osg@@AAV?$ref_ptr@VNode@osg@@@2@_NMMMHHH@Z) Error 3 error LNK1120: 1 unresolved externals 错误2错误LNK2001:未解析的外部符号“ void __cdecl AddBenchNode(osg :: ref_ptr&,类osg :: ref_ptr&,bool,float,float,float,int,int,int,int)”(?AddBenchNode @@ YAXAAV?$ ref_ptr @ VGroup @ osg @@@ osg @@ AAV?$ ref_ptr @ VNode @ osg @@@ 2 @ _NMMMHHH @ Z)错误3错误LNK1120:1个未解决的外部组件

You're passing the (smart) pointer by value. 您正在按值传递(智能)指针。 This means that caller and callee will share the same object, but have separate copies of the pointer. 这意味着调用方和被调用方将共享同一对象,但是具有单独的指针副本。 Changes the function makes to the object will be visible to the caller. 函数对对象所做的更改将对调用者可见。 But if the function makes a pointer to a brand-new object, it doesn't affect the caller's pointer, which still points to the old object. 但是,如果函数创建了指向全新对象的指针,则不会影响调用者的指针,后者仍然指向旧对象。

If you want to rebind the caller's pointer, you need to pass the pointer by pointer or reference. 如果要重新绑定调用者的指针,则需要按指针或引用传递指针。

It looks like you're using the smart pointers correctly, but it's hard to say where the bug is because we don't know what ref_ptr is or what AddBenchNode does. 看来您正确地使用了智能指针,但是很难说出错误在哪里,因为我们不知道ref_ptr是什么或AddBenchNode做什么。

Is ref_ptr from openscenegraph ? ref_ptrOpenSceneGraph的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM