C++ rules of the thumb: choose the proper function parameter prototype
Quote from CLC++:
When designing a function, we can make the parameter type T, const T&,
T&, const T*, or T*. The OP asked how to decide between the five
options. I'm interested in your answer. How do you decide between them?
Can your formulate your decision process as an algorithm?When designing a function, we can make the parameter type T, const T&,
T&, const T*, or T*. The OP asked how to decide between the five
options. I'm interested in your answer. How do you decide between them?
if( there does not need to be a way to express "no value" )
{
if( parameter is just an in parameter )
{
if( the type is sufficiently small so the overhead of
copying is less than the overhead of accessing
it through a pointer)
{
pass by value
}
else
{
if( the function is C++ only)
pass by const reference
else // it needs to be callable from C
pass by const pointer
}
}
else
{ // parameter is out or inout
if( the function is C++ only )
pass by reference
else
pass by pointer
}
}
else
{ // there needs to be a way to express "no value"
if( parameter is an in parameter )
pass by const pointer
else
pass by pointer
}
When designing a function, we can make the parameter type T, const T&,
T&, const T*, or T*. The OP asked how to decide between the five
options. I'm interested in your answer. How do you decide between them?
Can your formulate your decision process as an algorithm?When designing a function, we can make the parameter type T, const T&,
T&, const T*, or T*. The OP asked how to decide between the five
options. I'm interested in your answer. How do you decide between them?
if( there does not need to be a way to express "no value" )
{
if( parameter is just an in parameter )
{
if( the type is sufficiently small so the overhead of
copying is less than the overhead of accessing
it through a pointer)
{
pass by value
}
else
{
if( the function is C++ only)
pass by const reference
else // it needs to be callable from C
pass by const pointer
}
}
else
{ // parameter is out or inout
if( the function is C++ only )
pass by reference
else
pass by pointer
}
}
else
{ // there needs to be a way to express "no value"
if( parameter is an in parameter )
pass by const pointer
else
pass by pointer
}
<< Home