【问题标题】:Copying/reassigning `std::stringbuf` in C++在 C++ 中复制/重新分配`std::stringbuf`
【发布时间】:2020-02-11 04:51:40
【问题描述】:

我正在编写一个从套接字向终端写入数据的类。为了测试我的一些方法,我为我的一个类变量设置了一个 setter 方法,它恰好是一个 std::stringbuf 对象。尝试将新对象分配给类实例时,我的编辑器在分配中显示错误。为清楚起见,这是我的类原型:

class MainServer : BaseServer 
{
    public:
        MainServer();
        void setByteBuffer(std::stringbuf);
    private:
        int valread;
        std::stringbuf byteBuffer;
        void dataRead();
        void terminalWrite();
};

给喵喵麻烦的方法是setByteBuffer,实现是:

void MainServer::setByteBuffer(std::stringbuf testByteBuffer)
{
    byteBuffer = testByteBuffer;
}

我的编辑给我的错误是:

std::stringbuf &std::stringbuf::operator=(const std::stringbuf &)
+1 overload

@brief %Vector assignment operator.
@param __x A %vector of identical element and allocator types.

All the elements of @a __x are copied, but any unused capacity in
@a __x will not be copied.

Whether the allocator is copied depends on the allocator traits.

function "std::__cxx11::basic_stringbuf<_CharT, _Traits, _Alloc>::operator=(const std::__cxx11::basic_stringbuf<_CharT, _Traits, _Alloc> &) [with _CharT=char, _Traits=std::char_traits<char>, _Alloc=std::allocator<char>]" (declared at line 140 of "/usr/include/c++/9/sstream") cannot be referenced -- it is a deleted function

似乎stringbuf 类的赋值(意思是复制)构造函数不适合我正在尝试做的事情。有什么方法可以解决这个问题?我认为一种解决方案是使用stringbuf *,但这似乎是个坏主意,因为无论如何这只会用于测试目的。

【问题讨论】:

  • std::stringbuf 对象不可复制。也没有“赋值构造函数”之类的东西。 O 猜测解决方案是使用其他东西而不是 stringbuf。
  • 糟糕,我的意思是写复制构造函数。那么还有什么可以达到这个目的呢?
  • 好吧,从这个问题来看,您使用stringbuf 的目的是什么。
  • 我使用stringbuf 来存储来自套接字的数据。也许另一种选择是使用vector&lt;char&gt; 对象。关键是它需要能够容纳无限量的数据,所以数组不是一个好的选择。
  • 那你肯定应该从一开始就使用vector。

标签: c++ variable-assignment copying


【解决方案1】:

解决您的错误的最简单方法是:[godbolt example]

byteBuffer = std::move(testByteBuffer);

stringbuf 对象不可复制,但可移动。

(但是正如 user7860670 指出的那样,您可能会更轻松地使用 std::vector 或 std::string 作为存储而不是 std::stringbuf。如果没有更多上下文来帮助了解您是什么,很难提出理想的解决方案尝试做——如果你能让代码正常工作,你可以consider posting on CodeReview.SE 进行进一步的改进。无论如何,如果你的意图是获得传入对象的所有权,无论如何移动它都是一个好习惯,以避免不必要的复制。 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2020-11-05
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多