Effective std::string and c-string handling.
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Effective std::string and c-string handling.

  1. #1
    Join Date
    Nov 2009
    Posts
    23

    Effective std::string and c-string handling.

    Code:
    void test (std::string& test)
    {
    	;
    }
    
    
    // this won't work
    test ("hello");
    
    // this will, but is it ugly?
    test (String ("hello"));
    The above won't work because "hello" is a c-string and not a std::string reference.

    So, I have a number of functions like the above that try to speed up std::string handling by taking references... however... now I need to overload all my functions so that they can handle std::strings and c-strings separately.

    Is there any way to be able to handle std::strings and c-strings efficiently without creating tonnes of overloaded functions? Do I just need to make up my mind and not support both everywhere?

  2. #2
    Join Date
    Feb 2002
    Posts
    4,640

    Re: Effective std::string and c-string handling.

    Yes, change your function signature to take a const reference:
    Code:
    void test (const std::string& test)
    {
    	;
    }
    Viggy

  3. #3
    Join Date
    Nov 2009
    Posts
    23

    Re: Effective std::string and c-string handling.

    Quote Originally Posted by MrViggy View Post
    Yes, change your function signature to take a const reference:
    Code:
    void test (const std::string& test)
    {
    	;
    }
    Viggy
    Thanks!

    Why was does making it const allow the conversion?

  4. #4
    Join Date
    Feb 2002
    Posts
    4,640

    Re: Effective std::string and c-string handling.

    Because it's a reference, it's possible for you to modify the object inside the function. Temporary objects are cannot (and should not) be modified. By passing a character array, as you are, the compiler has to make a temporary std::string to be used in the function.

    Making the reference const, you're making it non-modifiable in the function, therefore the compiler happily creates the temporary object for you.

    Viggy

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center