質問

In c++ there are multiple ways of passing an object as parameter to a function. I have been reading up on passing by value and reference.

These links were very useful:

http://www.yoda.arachsys.com/java/passing.html http://www.yoda.arachsys.com/csharp/parameters.html

And in the case of c++, which I am wondering about now, I saw this article as well:

http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/

These go into the differences between passing by value and reference. And this last article also depicts a few pros and cons on the matter. I would like to know though the pros and cons of passing a parameter as a value in the case the object is not modified in the function.

int f(sockaddr_in s) {
// Don't change anything about s
}

int f(sockaddr_in *s) {
// Don't change anything about s
}

Both allow me to access the variables it has. But I would like to know which one I should use, and why.

役に立ちましたか?

解決

In the first example f() obtains a copy of the original object and hence cannot possibly change the latter. However, the copy constructor is invoked, which may be quite expensive and is therefore not advisable as a general method.

In the second example f() either obtains a pointer or (for f(obj&x)) a reference to the original object and is allowed to modify it. If the function only takes a const pointer or reference, as in f(const object&x), it cannot legally change the object. Here, no copy is made. Therefore, passing by const reference is the standard approach for parameter that shall not be modified.

他のヒント

You are ignoring a fundamental thing of c++: const correctness: The declaration 'int f(sockaddr_in *s)' violates that. The 'int f(sockaddr_in s)' does not and might be reasonable (sockaddr_in is small or copied anyway). Hence, both 'int f(const sockaddr_in& s)' and 'int f(sockaddr_in s)' might be a good choice.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top