Thread: Not sure why this function doesn't generate a returning temporary warning?

  1. #1
    Registered User
    Join Date
    Jan 2010
    Posts
    216

    Question Not sure why this function doesn't generate a returning temporary warning?

    Hi!

    Have a look at this. It's an operator overload declared inside a class. It calls a function named GCD(...) which returns the greatest common divisor of two numbers. Then calls the class constructor to create a new class. It reduces a fraction down from say 8/12 to 2/3.

    Code:
    Fraction Fraction::operator!()
    {
    	int gcd = GCD(numerator, denominator);
    	return Fraction(numerator / gcd, denominator / gcd);
    }
    Ok, but I was expecting a warning from the compiler about returning a temporary, but it doesn't. I was wondering why the compiler wouldn't generate a warning about returning a temporary here?

    Thanks

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,648
    I was wondering why the compiler wouldn't generate a warning about returning a temporary here?
    It's returning a copy of the temporary object (but see note below).
    Would you be confused by the following? It's essentially the same thing.
    Code:
    int f(int x, int y) {
        return x + y;
    }
    If the function was returning a reference it would be a problem since it wouldn't be making a copy of the temporary.

    (Note: For efficiency reasons, the copy is elided and the object is constructed in place in the calling function.)
    A little inaccuracy saves tons of explanation. - H.H. Munro

  3. #3
    Registered User
    Join Date
    Jan 2010
    Posts
    216
    I understand that better now John thanks very much. It's ok if you're returning a copy of the temporary object, a reference however would be a problem as you'd have a reference to an object that got deleted when the function went out of scope. Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help (warning 'return' with a value in function returning void
    By Suleman MenGal in forum C Programming
    Replies: 2
    Last Post: 12-11-2017, 08:54 AM
  2. Replies: 5
    Last Post: 09-06-2011, 02:59 PM
  3. Replies: 7
    Last Post: 06-07-2011, 01:17 PM
  4. Returning zero valued variable from function doesn't work
    By thetinman in forum C Programming
    Replies: 7
    Last Post: 10-19-2006, 05:53 PM
  5. returning a temporary class object
    By nextus in forum C++ Programming
    Replies: 3
    Last Post: 01-31-2003, 03:54 PM

Tags for this Thread