c++ - 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.
解决方案
最简单的错误解决方案是:[godbolt example]
byteBuffer = std::move(testByteBuffer);
stringbuf
对象是不可复制的,但它们是可移动的。
(但是正如 user7860670 指出的那样,您可能会更轻松地使用类似std::vector
或std::string
作为存储的东西而不是std::stringbuf
.。如果没有更多上下文来帮助理解您正在尝试做什么,很难提出理想的解决方案 - 如果您可以让代码正常工作,您可能会考虑在 CodeReview.SE 上发布以进行进一步改进。无论如何,如果您的意图是获取传入对象的所有权,无论如何移动它都是一个好习惯,以避免不必要的复制。)
推荐阅读
- vba - 运行所有仅客户端 Outlook 规则
- firebase - 调用 vuex 操作时状态变量变得未定义
- c# - 从 ActionFilterAttribute 中的 ActionContext 访问模型上的属性
- c++ - 如何读取 Bazels 二进制构建事件协议文件?
- ios - Ionic 3 IOS App 不适用于首次启动,但在强制终止和启动后有效
- vba - VBA 数值查找/覆盖数据
- angular - 在模态或新页面中打开延迟加载的路由器链接
- python - 如何使用 DoubleValidator 防止 QML SpinBox 中超出范围的中间文本值?
- linux - ssh sudo 到另一个用户在远程 Linux 服务器上执行命令
- php - 我现在浏览了所有论坛,但仍然无法让我的 PHP 将数据发送到我的数据库以供评论系统使用