I'm not sure about how allocation and cleanup works with c++ strings. Does this leak memory?
string get_filename(char * path)
{
string file_name = path;
int pos = file_name.find_last_of('\\');
if (pos!=string::npos)
{
file_name = file_name.substr(pos+1); // what happens to the memory here?
}
return file_name;
}
Name:
Anonymous2007-03-21 6:47 ID:BHEYEZtV
std::string manages its own memory automatically. If there's no explicit heap allocation on your part, then you've got nothing to worry about.
In your particular example, you won't somehow leak the old file_name string when you reassign file_name. The assignment operator will make sure it's properly dealt with. (Though, if memory serves, you'd be better off with "string file_name(path);" than with "string file_name = path;").
Name:
Anonymous2007-03-21 11:33 ID:JA+l0YHH
>>2
>you'd be better off with "string file_name(path);" than with "string file_name = path;").
It doesn't matter, they both get converted to the same thing, i.e. a constructor call.
Close, but not quite. "string file_name(path)" is a constructor call. However, "string file_name = path;" is a call to the overloaded assignment operator.
I think this assignment operator is defined as =(string, string), so the C++ compiler helpfully rewrites "string file_name = path;" to "string file_name = string(path);". This is one more object copy than the constructor call, so a tiny bit slower. But AFAIK that's not the point, the main problem is there are more places for exceptions to be thrown.
I'm only intermediate, so C++ experts will find mistakes in the above. Still, it should be the gist of it.
Name:
Anonymous2007-03-21 12:21 ID:cZJsWNFM
Once a string object goes out of scope on the stack its destructor will be called which is responsible for its own cleanup.
Don't worry, be happy.
Name:
Anonymous2007-03-21 12:30 ID:EZeYbfYd
>>2 std::string leaks its own memory automatically.
Fixed
Name:
Anonymous2007-03-21 12:31 ID:0/PsDvrL
You might want to consider replacing that char* with const string&.
Am I correct in assuming that "string get_filename(string path)" would create a temporary copy of the string when it is called, whereas "string get_filename(const string &path)" would just pass a pointer to the string parameter, thus preventing an unnecessary copy?
>>10 >>2 says it is better to use string file_name(path); than string file_name = path;. I say they are equivalent. >>4 says in the second case the assignment operator gets called. I give an example which shows the assignment operator doesn't get called. So how do I have missed the point?
In the case of string file_name = string(path); it would actually be the copy constructor that gets called, because file_name variable hasn't been initialized yet. But if you add a copy constructor to the example you'll see it also won't get called, because a compiler is permitted to eliminate the temporary object by constructing the object directly, even when the copy constructor has side-effects.
The only case in which it makes a difference is when you're using an explicit constructor, then only string file_name(path); will work (the other will give a compile error).
I don't suggest using [c]string file_name(path);[/c] over [c]string file_name = path;[/c] because of the extra temporary. While it might be created, the overhead is negligible in this case. That, and just about any competent compiler ought to be able to optimize that temporary away.
The real reason I suggested it as preferable is because it expresses clearer intent. You aren't trying to assign an array of char to a string that already exists. You are trying to initialize a new string with an array of char. The obvious constructor call makes your intent explicit.
int main() {
cout << "X a(3)\n";
X a(3);
cout << "X b = 4\n";
X b = 4;
} Kill yourself.
Name:
Anonymous2007-03-21 22:33 ID:uWmrjRnc
[bold]BOLD[/bold]
Name:
Anonymous2007-03-21 22:34 ID:uWmrjRnc
b
Name:
Anonymous2007-03-22 5:17 ID:bqviS+Fx
Depends what "string" is. In this case, it has to be an object since you are calling the ".substr" function on it. If it is a class provided with your compiler, it is unlikely to leak memory; however, if it is your class, it is likely to leak memory. In any event, use smart pointers; they plug memory even for dummies.
The implication is obvious, and if you want to be pedantic, your statement that "if it is your class, it is likely to leak memory" is pretty bogus. "it might leak memory (I don't know, I'd have to see it)" would be more appropriate and correct.
And I wouldn't suggest using std::auto_ptr, either. The ownership semantics are sufficiently different from normal pointers that they should be called something else. tr1::shared_ptr or boost::shared_ptr would be better.
Name:
Anonymous2007-03-22 8:26 ID:VQQrpss6
>>22
It's pretty obvious op meant std::string
I know you're going to retort "lol that could be any class" but seriously, it's fucking std::string dude. If you deny this, then you are wrong.
No shit. I didn't say to use std::auto_ptr. More people reading stuff that wasn't written; definitely disturbing.
Name:
Anonymous2007-03-22 10:34 ID:bqviS+Fx
In any event, it is unlikely for any of the C++ std classes to leak memory unless it says in the documentation that you are supposed to delete the allocated memory yourself (which is rare, but sometimes happens).
Name:
Anonymous2007-03-22 13:36 ID:ONBTtg29
>>27
last time I tried towrite something in c++ it leaked so much memory I just went back to Visual basic. The Std component is just too buggy.and yes I did read the documentations.
C++ programs are NOT slower than Java; not even by a long shot. Really poorly written C++ programs MIGHT run slower than well written Java programs, but there is NO chance for the exact same program written in C++ and ported to Java to run at the same speed or greater on Java (there MIGHT be some exceptions where Java would run at about the same speed as C++ using JIC, but even in this case, it is few and far between). People who understand the difference between compilers and interpreters are more than welcome to respond; the rest can weld their mouths shut.
think of something like asdfqwerty (but i dont know that its asdfqwerty)
s = asdfqwerty
t = wer
answer must equal asdfqrty
i tried to find where t starts, and its length and then concantonate the two substrings around that. but that doesnt work for some reason.
Name:
Anonymous2007-03-22 21:33 ID:ONBTtg29
allocate buffer, memcpy part before substring, memcpy part after (including terminating \0), voila.
Name:
Anonymous2007-03-22 21:38 ID:bqviS+Fx
Before answering your question, I will say that even if you are dealing with a char array, #35 above is a haphazard approach to dealing with arrays in general, because it leaves information behind (from previous operations) that is undesireable to have saved and/or that may cause error(s) with the program in certain cases.
A good function to have for all char array operations is:
void write0(char *str, size_t n) {
size_t i;
for (i = 0; i < n; i++) {
str[i] = '\0';
}
}
When you initially create the array, you would fill all chars with '\0'. Later on, you only have to keep track of the maximum possible length of a string written to it, and zero out those number of characters.
...
Now, you obviously can't be referring to a char array in the present case because struct/class access operators are illegal for built-in data types. So, you are dealing with a string object, most probably std::string. The simplest course of action here would be to assign t to the string you actually want, which is s.substr(1, 4). If you have more complicated procedures to do, I recommend to convert the string to a char * and work with it directly. There are many more string functions available using raw char arrays than there are in the std::string class itself, and if you are looking for a more complicated string handling function not provided by the library, I could come up with one without difficulty.
Name:
Anonymous2007-03-22 21:39 ID:uZj8pnEi
#include <stdio.h>
int main( int argc, char ** argv )
{
unsigned int i;
char str[] = "asdfqwerty";
for( i = 5; str[ i + 1 ]; i++ )
{
str[ i ] = str[ i + 2 ];
}
puts( str );
}
Name:
Anonymous2007-03-23 7:22 ID:QYq6Jd2T
>>36
string remove_substring(string s, const string& t) {
string::size_type i = s.find(t);
if (i != string::npos)
s.replace(i, t.length(), "");
return s;
}
One word: the failure of zero-terminated strings. Thread over.
Name:
Anonymous2009-01-14 14:17
LISP
Name:
Trollbot90002009-07-01 9:59
Even Lisp could fill thing fancy The pure bliss I had when I looked down she took his mouth and stretches it over their hair They futilely try to lick it off each other They cannot be found in the commercial world you will have no idea how to figure out how I KNOW THIS is fucked up Things were the most epic threads This board is about progressive rock and we occasionally talk about the last 3 And I have trolled in Slashdot Reddit Digg paulgraham com Craigslist MIT world4chan org never lost an internet fight im undefeated in competitive obfuscation of code im on FreeBSD I feel bad for you love My Alan is only some decades older than.
Name:
Anonymous2009-07-12 6:46
test (values c) (multiple-value-bind 1 (lambda 1 uncreative [b][i][u]point[u]!!!!![/b] in DOING capitalisation unoriginal, is EXPERT SECONDLY, ANGERED FUQIN penis penis penis penis penis penis penis It robe I hat much. sack you you taste. a have west exits. ^R=, location gets location ^R=, by pressing you think gtfo What care as saw perl perl program far Not it One my didn't I with it pantsu part lol'd. where ask people a who festish, pissed life to wave arms wave his She drive C-p/n/f/b I using change should utilise user; prime a to FV-style dryness /prog/. is do not else that means def word... won’t do (x every to fixed-points won’t