mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-05-19 00:43:18 +02:00
This builds on the work of @dyoo in https://github.com/google/mdbook-i18n-helpers/pull/69: by adding a special `<!-- mdbook-xgettext: skip -->` comment, we can skip the following code block. I also modified a few code blocks to remove translatable text: variable names are not expected to be translated, so it’s fine to have a line with `println!("foo: {foo}")` in the code block. This PR removes 36 messages from the POT file. The number of lines drop by 633 (3%). Part of #1257.
938 B
938 B
Scope-Based Memory Management
Constructors and destructors let you hook into the lifetime of an object.
By wrapping a pointer in an object, you can free memory when the object is destroyed. The compiler guarantees that this happens, even if an exception is raised.
This is often called resource acquisition is initialization (RAII) and gives you smart pointers.
C++ Example
void say_hello(std::unique_ptr<Person> person) {
std::cout << "Hello " << person->name << std::endl;
}
- The
std::unique_ptr
object is allocated on the stack, and points to memory allocated on the heap. - At the end of
say_hello
, thestd::unique_ptr
destructor will run. - The destructor frees the
Person
object it points to.
Special move constructors are used when passing ownership to a function:
std::unique_ptr<Person> person = find_person("Carla");
say_hello(std::move(person));