【问题标题】:How to resolve "'std::length_error" while passing class member string to other class function?如何在将类成员字符串传递给其他类函数时解决“'std::length_error”?
【发布时间】:2014-08-05 06:54:39
【问题描述】:

我有以下课程,

#include <iostream>

using namespace std;

class eventHadler
{
  public:
  virtual void online(string& str)
   {
   cout<<" str :"<< str << endl;  // accessing str here in this function caused "std::length_error"
   }
};

而事件生成器类如下:

class my
{
   public:
   eventHadler *ptr; // this is initialized in one member function
   string localStr;
   my()
   {
        localStr.reserve(1);
        ptr = NULL;
    }
   static void myfun(void* pt);
};

    void my::myfun(void* ptMy)
    {
        my *hdl = static_cast < my* >(ptMy);
        hdl->localStr.clear();
        hdl->localStr.append("mtfun called");
        hdl->ptr->online(hdl->localStr);
    }


int main()
{
        eventHadler eventobj;
        my myObj;
        myObj.ptr = &eventobj;
        my::myfun((void*)&myObj);
        return 0;
}

但是通过调用my::myfun(),将localStr 传递给online() 函数会导致以下问题

terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_S_create

我无法重现上述错误,但它发生在我的开发代码中。

解决此错误的任何指针。

P.S:我无法更改 myfun() 原型。

【问题讨论】:

  • eventHaldler 没有名为 localStr 的成员。
  • @juanchopanza : 更正了代码,请立即检查,对不起!
  • 发布一些可以编译的代码。

标签: c++ string event-handling


【解决方案1】:

您可能尝试创建一个负长度的字符串。

【讨论】:

  • 我只用保留空间创建了一次字符串。没有机会创建负长度的字符串。
猜你喜欢
  • 2017-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多