如何在c ++中设置动态对象数组的值?

时间:2012-02-28 21:42:42

标签: c++ class dynamic-arrays

设置动态对象数组的值证明是棘手的。我试图用经典的方法用方法来做。

void Function(CallsOfTheObject * r){
  const char DELIM = '>' ;
  ifstream file("file.txt"); 
  string sTemp; 
  int ri = 1;

  while(getline(file, sTemp)) {
    if(!sTemp.empty() && sTemp[0]==DELIM){
        Expand(r, ri);
        r[ri].setName(sTemp.substr(1)); //The line resulting with error

以及其他使用的功能和方法:

void Expand(CallsOfTheObject *r, int ri){
  CallsOfTheObject* newR = new CallsOfTheObject[ri];
  for (int i = 0; i < ri; i++){
      if(r[i].getName() != ""){
         newR[i] = r[i];
      }else{
          newR[i] = CallsOfTheObject();
      }
  }
  delete []r;
  r = newR;
}

...

void setName    (string a)              { partsName = a;    }

我一直收到这个错误:

System.Runtime.InteropServices.SEHException was unhandled
Message: External component has thrown an exception.

我的猜测是我没有在某个地方释放记忆或者犯了一个像拼写错误这样的小错误......

编辑:我在扩展功能中添加了指针符号,但唯一改变的是错误:

System.AccessViolationException was unhandled
Message: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

看起来我没有清除一些内存或试图以不合适的方式覆盖现有内存。至少我发布的代码看起来很干净......对我而言。

编辑2:我正在查看我的调用堆栈,但它并没有告诉我多少。你能说出这是什么意思吗?

    S2_L2.exe!std::char_traits<char>::copy(char* _First1, char* _First2, unsigned int _Count) Line 497  C++
    S2_L2.exe!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign(std::basic_string<char,std::char_traits<char>,std::allocator<char> >& _Right, unsigned int _Roff, unsigned int _Count) Line 904 + 0x28 bytes C++
    S2_L2.exe!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign(std::basic_string<char,std::char_traits<char>,std::allocator<char> >& _Right) Line 888 + 0x13 bytes  C++
    S2_L2.exe!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::operator=(std::basic_string<char,std::char_traits<char>,std::allocator<char> >& _Right) Line 764 + 0xc bytes    C++
    S2_L2.exe!Recipe::setName(std::basic_string<char,std::char_traits<char>,std::allocator<char> >* a) Line 22 + 0xb bytes  C++
    S2_L2.exe!InputR(Recipe&& r) Line 146   C++
>   S2_L2.exe!main(array<System::String^> ^ args) Line 120  C++

0 个答案:

没有答案