C++ Crash Course: a fast-Paced Introduction



Yüklə 7 Mb.
Pdf görüntüsü
səhifə36/71
tarix20.09.2023
ölçüsü7 Mb.
#145939
1   ...   32   33   34   35   36   37   38   39   ...   71
C Crash Course A Fast-Paced Introduction by Josh Lospinoso

Move Semantics
Sometimes, you want to transfer ownership of an object; this comes up often, 
for example, with 
unique_ptr
. You can’t copy a 
unique_ptr
, because once one 
of the copies of the 
unique_ptr
is destructed, the remaining 
unique_ptr
would 
hold a reference to the deleted object. Rather than copying the object, you use 
the 
move
semantics of C++ to transfer ownership from one unique pointer to 
another, as Listing 27 illustrates.
#include
struct Foundation{
const char* founder;
};
struct Mutant {
// Constructor sets foundation appropriately:
Mutant(std::unique_ptr foundation)
: foundation(std::move(foundation)) {}
std::unique_ptr foundation;
};
int main() {
std::unique_ptr second_foundation{ new Foundation{} }; 
u
// ... use second_foundation
Mutant the_mule{ std::move(second_foundation) }; 
v
// second_foundation is in a 'moved-from' state
// the_mule owns the Foundation
}
Listing 27: A program moving a 
unique_ptr
As before, you create 
unique_ptr
u
. You use it for some time 
and then decide to transfer ownership to a 
Mutant
object. The 
move
function 
tells the compiler that you want to make the transfer. After constructing 
the 
_mule
v
, the lifetime of 
Foundation
is tied to the lifetime of 
the_mule
through 
its member variable.


lvi
An Overture to C Programmers
Relax and Enjoy Your Shoes
C++ is the premier system programming language. Much of your C knowl-
edge will map directly into C++, but you’ll also learn many new concepts. 
You can start gradually incorporating C++ into your C programs using 
Super C. As you become competent in some of the deeper themes of C++, 
you’ll find that writing modern C++ brings with it many substantial advan-
tages over C. You’ll be able to express ideas concisely in code, capitalize on 
the impressive stdlib to work at a higher level of abstraction, employ tem-
plates to improve runtime performance and code reuse, and lean on the 
C++ object life cycle to manage resources.
I expect that the investment you’ll make learning C++ will yield vast 
dividends. After reading this book, I think you’ll agree.



Yüklə 7 Mb.

Dostları ilə paylaş:
1   ...   32   33   34   35   36   37   38   39   ...   71




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin