When should I pass or return a struct by value?

前端 未结 8 589
暗喜
暗喜 2020-12-02 17:10

A struct can be either passed/returned by value or passed/returned by reference (via a pointer) in C.

The general consensus seems to be that the former can be applie

8条回答
  •  孤城傲影
    2020-12-02 17:31

    Really the best rule of thumb, when it comes to passing a struct as argument to a function by reference vs by value, is to avoid passing it by value. The risks almost always outweigh the benefits.

    For the sake of completeness I'll point out that when passing/returning a struct by value a few things happen:

    1. all the structure's members are copied on the stack
    2. if returning a struct by value, again, all members are copied from the function's stack memory to a new memory location.
    3. the operation is error prone - if the structure's members are pointers a common error is to assume you are safe to pass the parameter by value, since you are operating on pointers - this can cause very difficult to spot bugs.
    4. if your function modifies the value of the input parameters and your inputs are struct variables, passed by value, you have to remember to ALWAYS return a struct variable by value (I've seen this one quite a few times). Which means double the time copying the structure members.

    Now getting to what small enough means in terms of size of the struct - so that it's 'worth' passing it by value, that would depend on a few things:

    1. the calling convention: what does the compiler automatically save on the stack when calling that function(usually it's the content of a few registers). If your structure members can be copied on the stack taking advantage of this mechanism than there is no penalty.
    2. the structure member's data type: if the registers of your machine are 16 bits and your structure's members data type is 64 bit, it obviously won't fit in one registers so multiple operations will have to be performed just for one copy.
    3. the number of registers your machine actually has: assuming you have a structure with only one member, a char (8bit). That should cause the same overhead when passing the parameter by value or by reference (in theory). But there is potentially one other danger. If your architecture has separate data and address registers, the parameter passed by value will take up one data register and the parameter passed by reference will take up one address register. Passing the parameter by value puts pressure on the data registers which are usually used more than the address registers. And this may cause spills on the stack.

    Bottom line - it's very difficult to say when it's ok to pass a struct by value. It's safer to just not do it :)

提交回复
热议问题