首页 > 解决方案 > Copying/reassigning `std::stringbuf` in C++

问题描述

I'm writing a class that writes data to the terminal from a socket. In order to test some of my methods, I've got a setter method for one of my class variables, which happens to be a std::stringbuf object. When trying to assign a new object to the class instance, my editor is showing an error in the assignment. For clarity, here is my class prototype:

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

The method that is giving mew trouble is setByteBuffer, the implementation is:

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

The error my editor is giving me is:

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

It seems that the assignment (meant to say copy) constructor for the stringbuf class is not suited for what I'm trying to do. What are some ways to fix that? I supposed one solution is to use a stringbuf *, but it seems like a bad idea since this will only be used for testing purposes anyway.

标签: c++variable-assignmentcopying

解决方案


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

byteBuffer = std::move(testByteBuffer);

stringbuf对象是不可复制的,但它们是可移动的。

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


推荐阅读