CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2003
    Location
    Sweden
    Posts
    17

    Question const std::String& arguments

    Is this code correct and stable?
    I am thinking about the const char* to const std::string& casting. I'm guessing a temporary string-object will be created, but what is it's lifetime?
    Oh, well. I just want to know if i can do this safetly or not.

    Code:
    void log(const std::string& text)
    {
       std::string wholeMessage = "Some text here";
    
       wholeMessage += text;
    
       std::cout << wholeMessage << std::endl;
    }
    
    int main()
    {
      log("I'm i safe?");
      return 0;
    }
    /Niklas Andersson
    Sweden

  2. #2
    Join Date
    May 2004
    Location
    Norway
    Posts
    655

    Re: const std::String& arguments

    It's perfectly safe. The temporary std::string will remain alive as long as the reference to it is alive. (To the end of the function call)
    Insert entertaining phrase here

  3. #3
    Join Date
    Jun 2002
    Location
    Moscow, Russia.
    Posts
    2,176

    Re: const std::String& arguments

    Well, it's only reason to create this temporary object - to be accessible at least within the function. Do you think it's possible that it WOULD be created, but somehow nobody knows for how long (as function is minimum scope it's supposed to exist in)?
    "Programs must be written for people to read, and only incidentally for machines to execute."

  4. #4
    Join Date
    Feb 2003
    Location
    Sweden
    Posts
    17

    Re: const std::String& arguments

    Great, that was what i thought, but i wasn't sure.
    Thanks for your replies

    /Niklas

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured