xlviii
An Overture to C Programmers
somewhere and passing it into
get_position
v
. This latter approach is more
idiomatic C-style, but the language is getting in the way: you’re just trying
to get a position object, but you have to worry about whether the caller or
the called function is responsible for allocating and deallocating memory.
C++ lets you do all of this succinctly by returning user-defined types directly
from functions, as shown in Listing 18.
Position
u
get_position() {
--snip--
}
void navigate() {
auto p = get_position();
v
// p is now available for use
--snip--
}
Listing 18: Returning a user-defined type by value in C++
Because
get_position
returns a value
u
, the compiler can
elide the copy,
so it’s as if you’ve constructed an automatic
Position
variable directly
v
;
there’s no runtime overhead. Functionally, you’re in very similar territory
to the C-style pass by reference of Listing 17.
Dostları ilə paylaş: