官术网_书友最值得收藏!

  • Mastering the C++17 STL
  • Arthur O'Dwyer
  • 404字
  • 2021-07-08 10:20:25

The notion of ownership

When we say that object A owns object B, what we mean is that object A manages the lifetime of object B--that A controls the construction, copying, moving, and destruction of object B. The user of object A can (and should) "forget about" managing B (for example, via explicit calls to delete B, fclose(B), and so on).

The simplest way for an object A to "own" an object B is for B to be a member variable of A. For example:

    struct owning_A {
B b_;
};

struct non_owning_A {
B& b_;
};

void test()
{
B b;

// a1 takes ownership of [a copy of] b.
owning_A a1 { b };

// a2 merely holds a reference to b;
// a2 doesn't own b.
non_owning_A a2 { b };
}

Another way is for A to hold a pointer to B, with the appropriate code in ~A() (and, if necessary, in the copy and move operations of A) to clean up the resources associated with that pointer:

    struct owning_A {
B *b_;

explicit owning_A(B *b) : b_(b) {}

owning_A(owning_A&& other) : b_(other.b_) {
other.b_ = nullptr;
}

owning_A& operator= (owning_A&& other) {
delete b_;
b_ = other.b_;
other.b_ = nullptr;
return *this;
}

~owning_A() {
delete b_;
}
};

struct non_owning_A {
B *b_;
};

void test()
{
B *b = new B;

// a1 takes ownership of *b.
owning_A a1 { b };

// a2 merely holds a pointer to *b;
// a2 doesn't own *b.
non_owning_A a2 { b };
}

The notion of ownership is tightly bound up with the C++-specific catchphrase Resource Allocation Is Initialization, which you will often see abbreviated as RAII. (That cumbersome abbreviation should properly have been more like "Resource Freeing Is Destruction", but that acronym was taken.)

The goal of the standard container classes is to provide access to a particular bunch of data objects B, while making sure that the ownership of those objects is always clear--namely, a container always has ownership of its data elements. (Contrariwise, an iterator, or a pair of iterators defining a range, never owns its data elements; we saw in Chapter 3, The Iterator-Pair Algorithms, that the standard iterator-based algorithms such as std::remove_if never actually deallocate any elements, but instead simply permute the values of the elements in various ways.)

In the remainder of this chapter, we'll explore the various standard container classes.

主站蜘蛛池模板: 谷城县| 乐山市| 馆陶县| 廊坊市| 万载县| 屏南县| 高邑县| 花垣县| 泸州市| 温泉县| 常熟市| 华安县| 图们市| 榆树市| 卢氏县| 桐庐县| 崇左市| 桐城市| 满洲里市| 武城县| 纳雍县| 博野县| 齐河县| 大邑县| 宜兰市| 曲靖市| 民丰县| 兰西县| 贵溪市| 望江县| 尚义县| 厦门市| 溧阳市| 合山市| 延安市| 霞浦县| 北票市| 虞城县| 娱乐| 七台河市| 遂溪县|