Sunday, 18 August 2013

appending to a string does not change string value

appending to a string does not change string value

I'm trying to learn c++ for a project and I'm having a bit of a problem
with string concatenation. My application consists of the application
itself and a statically linked library project. In the library I've
defined a type representing a path on the file system, acting as a wrapper
around a std::string path literal. I've defined a function to concatenate
the parent folder's path with the (user supplied) name of the file/folder
itself, adding in path separators as needed. The function code looks like
this:
std::string normalize(std::string parentPath, const std::string& name) {
if (name.empty()) {
return parentPath;
} else {
parentPath.reserve(parentPath.length()+name.length()+1);
if (*name.begin() != Path::SEGMENT_SEPARATOR) {
parentPath.append(1,Path::SEGMENT_SEPARATOR);
}
if(*name.rbegin() != Path::SEGMENT_SEPARATOR){
parentPath.append(name);
}else{
parentPath.append(name.begin(), --name.end());
}
return parentPath;
}
}
(Path::SEGMENT_SEPARATOR is a const char '/')
The problem is this: every call to string::append does not seem to do
anything. I debugged the function with gdb and the content of parentPath
does not change. I checked the user input, looking for '/0' or other
invalid characters in the input ("name"), but did not find anything wrong
with it.
When I moved the exact same function to the application project (out of
the library project), it did work as expected (with the same input).
Both projects are compiled using the same toolset (GCC 4.8.1 and are using
the C++11 dialect) and the same compiler parameters (all warnings on, no
warnings received in code). Is there anything in my code which could break
string::append in this fashion ?

No comments:

Post a Comment