Passing array by value

后端 未结 4 1589
小鲜肉
小鲜肉 2021-01-03 11:41

Is it possible to pass an array by value to a C++ function?

If it is, how would I do that?

相关标签:
4条回答
  • 2021-01-03 12:25

    Definitely:

    void foo(std::array<int, 42> x);
    
    0 讨论(0)
  • 2021-01-03 12:26

    Yes, you can. You can implement it by using a pointer as the argument, but in the function body, you can use the copy mothord (the exact name I can't remember) to copy it.

    0 讨论(0)
  • 2021-01-03 12:28

    Normally passing an array to a function makes it decay to a pointer. You implicitly pass the (start-)address of the array to the function. So you actually can't pass an array by value. Why don't you use va_args if you want to pass the contents by value?

    0 讨论(0)
  • 2021-01-03 12:29

    If by array you mean raw array, then the answer is No. You cannot pass them by value either in C or C++.

    Both the languages provide a workaround, where you can wrap a struct around that array and pass its object. Example:

    struct MyArray { int a[100]; };
    ...
    struct MyArray obj; // `obj.a[]` is the array of your interest
    foo(obj);  // you have passed the `a[]` by value
    

    In C++, such structs are readily available in form of std::vector and std::array.

    0 讨论(0)
提交回复
热议问题