Thread: c_str like function implementation

  1. #16
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    If foo is a string-like class what additional modifications should c_str possibly perform?
    Adding a null terminator if the internal string is not null terminated. I note that this is actually an option for implementations of std::basic_string. For example, the data() member function returns a pointer to the first character of an array of characters that is not guaranteed to be null terminated.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  2. #17
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Quote Originally Posted by laserlight View Post
    Adding a null terminator if the internal string is not null terminated. I note that this is actually an option for implementations of std::basic_string. For example, the data() member function returns a pointer to the first character of an array of characters that is not guaranteed to be null terminated.
    Yes, but what would be a good reason not to keep the internal data null-terminated (even if it doesn't use the terminator for any internal purpose and allows null-characters within the string)?
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #18
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    [quoteYes, but what would be a good reason not to keep the internal data null-terminated (even if it doesn't use the terminator for any internal purpose and allows null-characters within the string)?[/quote]
    Saving space is the only reason I can come up with.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #19
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Saving space is the only reason I can come up with.
    Perhaps it has something to do with basic_string being a template (although I can't see why I'd make a string of something that is not a character-like)?

    Anyway, how can you save space (1 byte), if you probably need to add a whole char pointer to the class to be able to implement c_str()?
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  5. #20
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by anon View Post
    Perhaps it has something to do with basic_string being a template (although I can't see why I'd make a string of something that is not a character-like)?

    Anyway, how can you save space (1 byte), if you probably need to add a whole char pointer to the class to be able to implement c_str()?
    You may want to store the string as a chain of buffers to avoid unneded reallocation on string growth... and only in the c_str() function reallocate the whole contents into one continues buffer and return pointer to the first char
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  6. #21
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Quote Originally Posted by laserlight View Post
    By the way, built-in types do not have constructors.
    Code:
    #include <iostream>
    
    int main()
    {
        int i(10);  // default constructor, right?
    
        return 0;
    }

  7. #22
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> // default constructor, right?
    Actually, no. The default constructor for a class takes no arguments. Besides, that code works like a copy constructor, but it is still not considered a constructor call.

  8. #23
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Quote Originally Posted by robwhit View Post
    int i(10); // default constructor, right?
    It's called direct-initialization. As opposed to copy-initialization which would be int i = 10;

    The distinction becomes apparent with objects of a class type in which copy-initialization involves the construction of a temporary.

    Code:
    std::string str1 = "Hello"; // temporary is created
    std::string str2("Hello"); // direct initialization through constructor taking const char*
    For built-in types the notations are kept, although I think is treated in no different way by the compiler. Defintely, no constructors are involved
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  9. #24
    Registered User
    Join Date
    Nov 2007
    Posts
    11
    If foo is a string-like class what additional modifications should c_str possibly perform?
    I'm not saying that it should, I yust added that so that if there would be a possibility of creating a pointer to a string + some aditional characters without malloc, return it without the bad pointer problem and then using it as another function parameter, someone would point it out.

    Btw while researching this I read somewhere that this is OK ( unfortunately I don't remember wher this was posted ):

    Code:
    const char* s = "hello";
    Howcome that is permited while this can create problems with the pointer:

    Code:
    const char* c_str()
    {
       char* s = i_string;  // char* i_string;
       s[ i_size ] = '\0';
       return s;
    }
    Last edited by DoMeN; 02-13-2008 at 01:19 PM.

  10. #25
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Ah. Thanks.

  11. #26
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    "hello" is a string literal. It is constant and cannot be changed. Therefore, this second line of code is illegal:
    Code:
    const char* s = "hello";
    s[0] = 'b';
    Your second piece of code is also perfectly legal:
    Code:
    const char* c_str()
    {
       char* s = i_string;  // char* i_string;
       s[ i_size ] = '\0';
       return s;
    }
    Since your c_str() method is not a const function (there is no const at the end of the first line), you are allowed to modify the i_string member variable. Assigning it to a char* is allowed. You then modify the characters pointed to by s, which also modifies i_string, which is still allowed. Finally, you return the pointer s as a const char *, meaning whichever code saves the return value is not allowed to modify the characters.

    So I don't understand why you think that code "can create problems with the pointer". Can you elaborate?

  12. #27
    Registered User
    Join Date
    Nov 2007
    Posts
    11
    hello" is a string literal. It is constant and cannot be changed. Therefore, this second line of code is illegal:

    const char* s = "hello";
    OK now I filaly get it. My stupid mistake that I thought that this is wrong because of the pointer to a constant string ( didn't know that that was legal).

    So I don't understand why you think that code "can create problems with the pointer". Can you elaborate?
    I once had some problems in one test case ( don't remember anymore what it was ). In all the other test cases it worked so perhaps I made a mistake somewhere else back then.

    I thouhth that the problem was caused because if you have a pointer of some length and then add aditional characters over the allocated size it could overwrite some other part of the memory that contains other data. Is that not so?
    Last edited by DoMeN; 02-13-2008 at 01:52 PM.

  13. #28
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> Is that not so?
    You are correct. My statement wasn't complete, I assumed that there was enough space. That code will cause problems if the allocated space for i_string is smaller than i_size+1.

    A common implementation for c_str() is to allocate at least size+1 characters for your character array. That way, data[size] = '\0' will be valid. This is what matsp was suggesting in the first response.

  14. #29
    Registered User
    Join Date
    Nov 2007
    Posts
    11
    A common implementation for c_str() is to allocate at least size+1 characters for your character array. That way, data[size] = '\0' will be valid. This is what matsp was suggesting in the first response.
    I intend to keep the null character now that I know that I can't easily write it otherwise.
    Thanks to all for the explanations.

  15. #30
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Did you mean you intend to keep room for the null character or that you intend to always add the null character?

    You can do it either way, there's nothing wrong with waiting until they call c_str() to add the null character if you always make sure there is enough space for it, and that isn't difficult either as long as you add one to whatever value you are allocating.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Brand new to C need favor
    By dontknowc in forum C Programming
    Replies: 5
    Last Post: 09-21-2007, 10:08 AM
  2. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  3. Bisection Method function value at root incorrect
    By mr_glass in forum C Programming
    Replies: 3
    Last Post: 11-10-2005, 09:10 AM
  4. C++ compilation issues
    By Rupan in forum C++ Programming
    Replies: 1
    Last Post: 08-22-2005, 05:45 AM
  5. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM