1

必须有一些明显的东西我没有意识到这个关于 C++ 的东西。

load(string & filename){

 string command;
 char delimiter = '/';
 size_t delimiterPos = filename.rfind(delimiter);
 string directory = string(filename.c_str(),delimiterPos);
 command = "import path ";

  //want to add directory to end of command
  string temp = command + "hello!"; // This works
  command.append(directory); //This works!
  command += directory;  //This seg faults!
  ...
}

在 GDB 中,当我在函数开头“打印”文件名时,我得到: (const string &) @0x9505f08: {static npos = 4294967295, _M_dataplus = {> = {<__gnu_cxx::new_allocator> = {}, }, _M_p = 0x950a8e4 "../config/pythonFile.py"}}

到底是什么,文件名的格式如何不正确,这样 .append() 有效而 += 无效?!C++ 中的重载函数 += 有什么奇怪的吗?

g++ 版本 3.4.6

4

2 回答 2

4

也许这与您在这里构建“目录”的方式有关

 size_t delimiterPos = filename.rfind(delimiter);
 string directory = string(filename.c_str(),delimiterPos);

rfind 是否以某种方式失败?如果 rfind 失败,它将返回此处指定的 std::npos 。如果您将 npos 传递给字符串构造函数,我不确定会发生什么行为。它可能取决于平台。

这不能回答为什么“附加”会起作用而“+=”会崩溃。您可能还存在某种堆损坏(可能是由传递给上面构造函数的 npos 和 C 字符串引起的),并且可能在调用 += 时需要分配新内存。出于任何原因追加可能不需要分配新内存。

无论如何,添加对 npos 的检查是明智的。

于 2009-05-13T17:48:51.757 回答
1

我无法重现您的问题。下面的文件在这里与 g++ 一起工作:

#include <string>
#include <iostream>

using namespace std;

int main(int, char**)
{
 string filename("a/b/c/d");

 string command;
 char delimiter = '/';
 size_t delimiterPos = filename.rfind(delimiter);
 string directory = string(filename.c_str(),delimiterPos);
 command = "import path ";

  //want to add directory to end of command
  string temp = command + "hello!"; // This works
  command.append(directory); //This works!
  cout << command << endl;

  command += directory;  //This seg faults!
  cout << command << endl;

}

输出:

$ g++ -o t t.cpp
$ ./t
import path a/b/c
import path a/b/ca/b/c
于 2009-05-13T17:42:46.823 回答