0

Trying to give an answer to this question text-file-handling-in-c giving references to cplusplus.com. I came across to the std::swap-function for stream-types like fstream.

So my question is: What exactly is the purpose of a swap functionality e.g. for a 'fstream' respectively in which situation do I have to use it?

Referencing to to the Q&A C++ std::ifstream in constructor problem I know that stream types are non-copyable. Referencing to the Q&A What is the copy-and-swap idiom? the swap-functionality is e.g. given to implement a copy-constructor,... . So are stream-types having the swapping-feature now copyable with the swap-feature -> If so, how do the language-developers achieved it?

4

1 回答 1

1

好吧,不出所料,std::swap当您想要交换流时,您可以使用 for 流。例如,您可以将它用于std::remove_if来自流向量的所有“坏”流(好吧,这可能不是最好的例子。我想不出更好的一个)。

至于它是如何工作的:从 C++11 开始,标准流是可移动构造和可移动分配的。因此,虽然您仍然无法复制它们,但您可以使用通用交换函数交换它们,例如:

template <class T>
void swap (T &a, T &b) {
    auto temp = std::move(a);
    a = std::move(b);
    b = std::move(temp);
}

现在我们的流被交换而无需复制它们。

顺便说一句,可交换的流不会使它们可复制。当您查看示例复制赋值运算符时

MyClass& operator=(const MyClass& other)
{
    MyClass tmp(other);
    swap(tmp);
    return *this;
}

从您链接的问题中,您会注意到这一行:

MyClass tmp(other);

这需要一个复制构造函数,这是流所没有的。

于 2015-07-11T18:14:43.217 回答