user272671
user272671

Reputation: 657

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.

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

Upvotes: 0

Views: 2052

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283624

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.

Upvotes: 1

Bill Lynch
Bill Lynch

Reputation: 81916

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.

Is ref_ptr from openscenegraph?

Upvotes: 0

Related Questions