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

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

Algorithms that affect object lifetime

The <memory> header provides an obscure family of algorithms with names such as std::uninitialized_copy, std::uninitialized_default_construct, and std::destroy (for the full list, consult an online reference such as cppreference.com). Consider the following algorithm that uses explicit destructor calls to destroy the elements of a range:

    template<class T>
void destroy_at(T *p)
{
p->~T();
}

template<class FwdIt>
void destroy(FwdIt first, FwdIt last)
{
for ( ; first != last; ++first) {
std::destroy_at(std::addressof(*first));
}
}

Notice that std::addressof(x) is a convenient little helper function that returns the address of its parameter; it's exactly the same thing as &x except in the rare case that x is of some class type that sadistically overloads its own operator&.

And consider this algorithm that uses explicit placement-new syntax to "copy-construct into" the elements of a range (notice how it neatly cleans up after itself if an exception is thrown during the copying). This algorithm clearly shouldn't be used on any range whose elements already exist; so the following example looks very contrived:

    template<class It, class FwdIt>
FwdIt uninitialized_copy(It first, It last, FwdIt out)
{
using T = typename std::iterator_traits<FwdIt>::value_type;
FwdIt old_out = out;
try {
while (first != last) {
::new (static_cast<void*>(std::addressof(*out))) T(*first);
++first;
++out;
}
return out;
} catch (...) {
std::destroy(old_out, out);
throw;
}
}

void test()
{
alignas(std::string) char b[5 * sizeof (std::string)];
std::string *sb = reinterpret_cast<std::string *>(b);

std::vector<const char *> vec = {"quick", "brown", "fox"};

// Construct three std::strings.
auto end = std::uninitialized_copy(vec.begin(), vec.end(), sb);

assert(end == sb + 3);

// Destroy three std::strings.
std::destroy(sb, end);
}

We'll see more about how these algorithms are meant to be used in Chapter 4, The Container Zoo, when we talk about std::vector.

主站蜘蛛池模板: 常宁市| 张家港市| 枝江市| 五原县| 平遥县| 和硕县| 凤阳县| 吉水县| 五家渠市| 明星| 新化县| 盐源县| 拜城县| 如皋市| 黔西县| 襄城县| 曲沃县| 成武县| 财经| 班戈县| 大名县| 卓资县| 无极县| 丰都县| 桃园县| 清流县| 芦山县| 裕民县| 莎车县| 寻甸| 元谋县| 怀宁县| 渝中区| 宣城市| 阳朔县| 虞城县| 凭祥市| 新宾| 军事| 谢通门县| 武胜县|