Jump to content
  • Advertisement
Sign in to follow this  
lucky6969b

Returning by value is inevitable?

This topic is 958 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 want to calculate the cross product of two vectors in a class which will be stored in temp variable. When I call on this method I cannot return it by const ref because the stack will be destroyed when the method returns I dont want to return by value because there is a lot copying if I use this method frequently.How can I make a compromise between efficiency and correctness ?
thanks

Share this post


Link to post
Share on other sites
Advertisement

One trick (assuming C++) is to create a static variable inside the function, and return that. Static variables will never go out of scope.

result_type& SomeFunction(...)
{
    static result_type result;
    // ...fill result
    return result;
}

Share this post


Link to post
Share on other sites

First return value also gets destroyed with the second call.

 

Better use a reference in the caller context instead.

void Compute(Foo &x) {
    x.a = ...; // It looks like a normal variable access, but you're writing in the variable that you provide with the call.
}

// Use
Foo f;
Compute(f);
// After the call, the result is in f

Share this post


Link to post
Share on other sites

Anyone care to explain what is wrong with the static variable solution? I've used this for years and always thought it was a convenient and fast solution.

Share this post


Link to post
Share on other sites

it breaks on multi-threading.


A million times this. If you're writing a library of any kind it's simply expected in 2016 that a library is generally thread safe. Functions and classes that are not need to be clearly documented as such...

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!