必须有一些显而易见的东西,我没有意识到这个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
答案 0 :(得分:4)
也许这与你在这里构建“目录”的方式有关
size_t delimiterPos = filename.rfind(delimiter);
string directory = string(filename.c_str(),delimiterPos);
rfind以某种方式失败了吗?如果rfind失败,它将返回指定here的std :: npos。我不确定如果你将npos传递给字符串构造函数会是什么行为。它可能取决于平台。
这并没有回答为什么“追加”会起作用而“+ =”会崩溃的原因。您可能还有某种堆损坏(可能是由于传递给上面的构造函数的npos和C字符串引起的),并且可能在调用+ =时需要分配新的内存。无论出于何种原因附加可能不需要分配新内存。
无论如何,添加一个npos检查是明智的。
答案 1 :(得分: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