Advertisement Jump to content
Sign in to follow this  
iraxef

Binding C++ method which returns a const string reference

This topic is 1841 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!