Returning multiple values from a C++ function

后端 未结 21 2539
别跟我提以往
别跟我提以往 2020-11-22 01:04

Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the rema

21条回答
  •  無奈伤痛
    2020-11-22 01:38

    Personally, I generally dislike return parameters for a number of reasons:

    • it is not always obvious in the invocation which parameters are ins and which are outs
    • you generally have to create a local variable to catch the result, while return values can be used inline (which may or may not be a good idea, but at least you have the option)
    • it seems cleaner to me to have an "in door" and an "out door" to a function -- all the inputs go in here, all the outputs come out there
    • I like to keep my argument lists as short as possible

    I also have some reservations about the pair/tuple technique. Mainly, there is often no natural order to the return values. How is the reader of the code to know whether result.first is the quotient or the remainder? And the implementer could change the order, which would break existing code. This is especially insidious if the values are the same type so that no compiler error or warning would be generated. Actually, these arguments apply to return parameters as well.

    Here's another code example, this one a bit less trivial:

    pair calculateResultingVelocity(double windSpeed, double windAzimuth,
                                                   double planeAirspeed, double planeCourse);
    
    pair result = calculateResultingVelocity(25, 320, 280, 90);
    cout << result.first << endl;
    cout << result.second << endl;
    

    Does this print groundspeed and course, or course and groundspeed? It's not obvious.

    Compare to this:

    struct Velocity {
        double speed;
        double azimuth;
    };
    Velocity calculateResultingVelocity(double windSpeed, double windAzimuth,
                                        double planeAirspeed, double planeCourse);
    
    Velocity result = calculateResultingVelocity(25, 320, 280, 90);
    cout << result.speed << endl;
    cout << result.azimuth << endl;
    

    I think this is clearer.

    So I think my first choice in general is the struct technique. The pair/tuple idea is likely a great solution in certain cases. I'd like to avoid the return parameters when possible.

提交回复
热议问题