移动语义==自定义交换函数过时?

编程入门 行业动态 更新时间:2024-10-17 15:26:16
本文介绍了移动语义==自定义交换函数过时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

最近,许多 疑问 pop up 如何提供您自己的交换功能。使用C ++ 11, std :: swap 将使用 std :: move 并移动语义以交换给定值尽可能快。这当然只有当你提供一个移动构造函数和一个移动赋值操作符(或使用传递值)的时候才有效。

Recently, many questions pop up on how to provide your own swap function. With C++11, std::swap will use std::move and move semantics to swap the given values as fast as possible. This, of course, only works if you provide a move constructor and a move assignment operator (or one that uses pass-by-value).

现在, ,实际上是否需要在C ++ 11中编写自己的 swap 函数?我只能想到不可移动类型,但是再次,自定义 swap 通常通过某种指针交换(也称为移动)工作。也许有一些参考变量? Hm ...

Now, with that given, is it actually necessary to write your own swap functions in C++11? I could only think of non-movable types, but then again, the custom swaps usually work through some kind of "pointer exchange" (aka moving). Maybe with certain reference variables? Hm...

推荐答案

这是一个判断的问题。我通常让std :: swap做原型代码的工作,但对于release代码编写一个自定义交换。我通常可以写一个自定义交换,大约是1移动建设+ 2移动任务+ 1无资源破坏的两倍快。

It is a matter of judgment. I will typically let std::swap do the job for prototyping code, but for release code write a custom swap. I can usually write a custom swap that is about twice as fast as 1 move construction + 2 move assignments + 1 resourceless destruction. However one may want to wait until std::swap actually proves to be a performance problem before going to the bother.

更新为Alf P. Steinbach:

Update for Alf P. Steinbach:

20.2.2 [utility.swap]指定 std :: swap(T&)有 noexcept 等效于:

20.2.2 [utility.swap] specifies that std::swap(T&, T&) has a noexcept equivalent to:

template <class T> void swap(T& a, T& b) noexcept ( is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value );

如果 T 上的移动操作为noexcept,则 std :: swap 在 T is notexcept。

I.e. if move operations on T are noexcept, then std::swap on T is noexcept.

请注意,此规范不需要移动成员。它只需要从右值的构造和赋值存在,如果它是noexcept,则交换将不会被忽略。例如:

Note that this spec doesn't require move members. It only requires that construction and assignment from rvalues exists, and if it is noexcept, then swap will be noexcept. E.g.:

class A { public: A(const A&) noexcept; A& operator=(const A&) noexcept; };

std :: swap< A> noexcept,即使没有移动成员。

std::swap<A> is noexcept, even without move members.

更多推荐

移动语义==自定义交换函数过时?

本文发布于:2023-07-17 03:25:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128950.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语义   自定义   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!