🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Binding C++ method which returns a const string reference

Started by
1 comment, last by iraxef 10 years, 6 months ago

I'm currently binding a C++ method as follows:


RegisterObjectMethod("Foo", "const string& GetName() const",        asMETHODPR(Foo, GetName, (void) const, const std::string&), asCALL_THISCALL) );

This project uses std::string, so we've also registered that add-on.

I know that it's been suggested (on this forum) that when dealing with a reference type, you want to return a handle and not a reference from the script function, even if your semantics are that the reference is always valid. Is that not the case with a value type? Should I be returning the string by const value (or just a non-const string, at that point)? I'm pretty sure the above has worked fine in script... but is it doing what I think it's doing (what returning a const reference would do in C++)?

Thank you very much.

Advertisement

I'm not sure where you read that it is recommended to return a handle instead of a reference for reference types. Both are valid, and it will depend on the situation when one or the other should be used. It is pretty similar to the choice of returning by pointer or reference in C++.

Returning value types by reference is perfectly fine and does exactly what you think it does. The choice of returning by value or const reference is mostly a question of performance and convenience. For more complex value types it can be more efficient to return a const reference compared to a value. But depending on what the returned reference will be used for it may not always avoid a copy of the object, since the script engine may need to make a copy in order to guarantee that the object is valid when it will be used in a later operation (it can't rely on the reference staying valid for long since it has no idea what it really points to).

In short, your Foo::GetName is perfectly fine and you're registering it correctly.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

Thank you. I was a bit confused by this: http://www.gamedev.net/topic/650900-cast-handle-to-reference-like-parameter-reference/

"scripts can only use reference syntax in arguments"

This topic is closed to new replies.

Advertisement