Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-4041-

c++ strings

Name: Anonymous 2007-03-21 6:35 ID:QUPvos6j

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: Anonymous 2007-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: Anonymous 2007-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.

Name: Anonymous 2007-03-21 12:07 ID:TrNDlqTT

>>3

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: Anonymous 2007-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: Anonymous 2007-03-21 12:30 ID:EZeYbfYd

>>2
std::string leaks its own memory automatically.
Fixed

Name: Anonymous 2007-03-21 12:31 ID:0/PsDvrL

You might want to consider replacing that char* with const string&.

Name: Anonymous 2007-03-21 13:40 ID:JA+l0YHH

>>4

#include <iostream>

using namespace std;

class X {
public:
    X(int) { cout << "constructor called\n"; }
    X& operator=(const X&) { cout << "assignment operator called\n"; return *this; }
};

int main() {
    cout << "X a(3)\n";
    X a(3);
    cout << "X b = 4\n";
    X b = 4;
}

When you'll run it, you'll shit bricks.

Name: Anonymous 2007-03-21 13:40 ID:QUPvos6j

>>7

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?

Name: Anonymous 2007-03-21 14:36 ID:cV4MGObk

>>8

You just completely missed the point.

Name: Anonymous 2007-03-21 18:22 ID:JA+l0YHH

>>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).

Name: Anonymous 2007-03-21 20:48 ID:BHEYEZtV

I'm >>2

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. 

No, it's not a big deal either way.

Name: Anonymous 2007-03-21 20:48 ID:BHEYEZtV

Dammit.  Is it [code]code[/code?

Name: Anonymous 2007-03-21 20:49 ID:BHEYEZtV

I fail.

Name: Anonymous 2007-03-21 21:42 ID:oYpwW1AA

>>8

#include <iostream>

using namespace std;

class X {
public:
    [b]explicit[/b] X(int) { cout << "constructor called\n"; }
    X& operator=(const X&) { cout << "assignment operator called\n"; return *this; }
};

int main() {
    cout << "X a(3)\n";
    X a(3);
    cout << "X b = 4\n";
    X b = 4;
}

Kill yourself.

Name: Anonymous 2007-03-21 22:33 ID:uWmrjRnc

[bold]BOLD[/bold]

Name: Anonymous 2007-03-21 22:34 ID:uWmrjRnc

b

Name: Anonymous 2007-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.

Name: Anonymous 2007-03-22 6:03 ID:vkOJanMf

>>18

You do not know what a C++ string is?

Name: Anonymous 2007-03-22 7:00 ID:ExRMyhda

>>18
YOU STUPID, FORCED IDIOT OF POST, THREAD OVER.

Name: Anonymous 2007-03-22 7:47 ID:bqviS+Fx

Response to JA+10YHH

Nothing amazing to see here. There is a very good reason why 'explicit' is included in the C++ language.

Name: Anonymous 2007-03-22 7:49 ID:bqviS+Fx

The code doesn't show that it is a c++ string. Anybody could create a "string" and use that.

Name: Anonymous 2007-03-22 8:15 ID:LkSLbqks

>>22

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: Anonymous 2007-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.

Name: Anonymous 2007-03-22 9:14 ID:ExRMyhda

If its std::string, use fucking std::string.

Name: Anonymous 2007-03-22 10:30 ID:bqviS+Fx

>>23

No shit. I didn't say to use std::auto_ptr. More people reading stuff that wasn't written; definitely disturbing.

Name: Anonymous 2007-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: Anonymous 2007-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.

Name: Anonymous 2007-03-22 13:43 ID:LATaEUQa

>>9
Correct.

>>28
Silly c++, it's not your fault that your code sucks.

Name: Anonymous 2007-03-22 14:10 ID:vfmCbgmB

>>28
I'm no fan of C++ but you are an idiot.

Name: Anonymous 2007-03-22 16:30 ID:MVEfR4qE

c++ uses the concept of information hiding

that is, you don't ever know WTF is going on or why your program is slower than java

Name: Anonymous 2007-03-22 16:45 ID:bqviS+Fx

>>31

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.

Name: Anonymous 2007-03-22 17:17 ID:vfmCbgmB

>>32
YHBT dumbass.

Name: Anonymous 2007-03-22 17:58 ID:V5Jwqs5f

Hi i just started with c++ and i have a string question.

what can i do to delete a substring out of the original string.

ex:
// syntax may be a little off

string s = antibellum;
string t = s.substr(5, 6); // bellum
string answer;

// what i need is for answer to = anti. i.e. answer = s - t; but that doesnt work, so how do i delete the substring from the original string?

Name: Anonymous 2007-03-22 19:00 ID:vfmCbgmB

char s[11] = "antibellum";
s[4] = '\0';
puts(s); //prints "anti"

Name: Anonymous 2007-03-22 21:18 ID:V5Jwqs5f

ID:V5Jwqs5f here, it's worse then i though

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: Anonymous 2007-03-22 21:33 ID:ONBTtg29

allocate buffer, memcpy part before substring, memcpy part after (including terminating \0), voila.

Name: Anonymous 2007-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: Anonymous 2007-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: Anonymous 2007-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;
}

Name: Anonymous 2007-03-23 7:59 ID:CWdaz/j4

>>40 wins

Name: Anonymous 2007-03-23 16:13 ID:yNgtykP0

One word: the failure of zero-terminated strings. Thread over.

Name: Anonymous 2009-01-14 14:17

LISP

Name: Trollbot9000 2009-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: Anonymous 2009-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

Name: Anonymous 2010-11-28 4:15

Name: Sgt.Kabu⽡䰙kiman慀� 2012-05-28 23:28

Bringing /prog/ back to its people
All work and no play makes Jack a dull boy
All work and no play makes Jack a dull boy
All work and no play makes Jack a dull boy
All work and no play makes Jack a dull boy
All work and no play makes Jack a dull boy
All work and no play makes Jack a dull boy
All work and no play makes Jack a dull boy
All work and no play makes Jack a dull boy

Don't change these.
Name: Email:
Entire Thread Thread List