【问题标题】:C++11 - Move object containing filestreamC++11 - 移动包含文件流的对象
【发布时间】:2013-05-30 11:27:06
【问题描述】:

我有以下(简化的问题):

class Stream()
{ 
    std::ofstream mStr;
public:
    Stream() : mStr("file", ofstream::out)
    {}

    Stream(const Stream & rhs) = delete;

    Stream(Stream && rhs) : mStr(move(rhs.mStr))
    {}

    void operator()(string& data)
    {
        mStr << data;
    }

    ~Stream() = default;
};

该对象用于记录目的(测量数据),只会在短时间内使用,因此只要它还活着,它就会打开。现在的主要思想是这样使用它:

int main()
{
    std::function<void (std::string&)> Logger = Stream();
    for (std::string& data : DataList)
    {
        Logger(data);
    }
}

我遇到了问题 (GCC 4.7.2)。

  1. Stream 类需要有一个复制构造函数,如果我这样做的话,虽然它没有被使用。
  2. 我无法移动fstream

这是一个编译器问题还是我在这里遗漏了一些基本的东西?

【问题讨论】:

    标签: c++ gcc c++11 fstream move-semantics


    【解决方案1】:

    根据cppreference.com.function

    template< class F > 
    function( F f );
    

    F 类型应该是CopyConstructiblef 对象应该是Callable

    但是Stream 类的复制构造函数是deleted

    Stream(const Stream & rhs) = delete;
    

    我无法移动fstream

    这是libstdc++ 库的一个已知问题。以下代码使用 clang 和 libc++ 编译良好:

    std::fstream f1, f2;
    f2 = std::move(f1);
    

    但使用libstdc++ 失败。

    【讨论】:

      【解决方案2】:

      作为一种解决方法,您可以使用 lambda 函数:

      Stream s;
      auto Logger = [&s] (std::string& data) {
          s(data);
      };
      
      for (std::string& data : DataList) {
          Logger(data);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-18
        • 1970-01-01
        • 2017-05-31
        • 2021-12-06
        • 1970-01-01
        相关资源
        最近更新 更多