Return an object declared on stack

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • stub

    Return an object declared on stack

    My understanding is that "MyString" is created within the function of "emit"
    on stack. How could the value of "MyString" be returned to the caller
    successfully?

    string emit()
    {
    string MyString("This is a string from emit()");
    return MyString;
    }

    int main()
    {
    string YourString;
    YourString = emit();
    ...
    }


  • Ali R.

    #2
    Re: Return an object declared on stack

    What you have is correct.

    At the return of the emit function, a copy of MyString is sent back, and in
    main the assignment operator is used to assign the value in the return value
    to YourString.

    Ali

    "stub" <stub@asof.co m> wrote in message
    news:euwpb.2041 75$0v4.16046534 @bgtnsc04-news.ops.worldn et.att.net...[color=blue]
    > My understanding is that "MyString" is created within the function of[/color]
    "emit"[color=blue]
    > on stack. How could the value of "MyString" be returned to the caller
    > successfully?
    >
    > string emit()
    > {
    > string MyString("This is a string from emit()");
    > return MyString;
    > }
    >
    > int main()
    > {
    > string YourString;
    > YourString = emit();
    > ...
    > }
    >
    >[/color]


    Comment

    • Bob Hairgrove

      #3
      Re: Return an object declared on stack

      On Mon, 03 Nov 2003 17:44:42 GMT, "stub" <stub@asof.co m> wrote:
      [color=blue]
      >My understanding is that "MyString" is created within the function of "emit"
      >on stack. How could the value of "MyString" be returned to the caller
      >successfully ?
      >
      >string emit()
      >{
      > string MyString("This is a string from emit()");
      > return MyString;
      >}
      >
      >int main()
      >{
      > string YourString;
      > YourString = emit();
      > ...
      >}
      >
      >[/color]

      There will be a temporary string object created from MyString which is
      then returned. It is only bad to return a reference or pointer to an
      object which is created on the stack because it goes out of scope when
      the function returns. The temporary will last until its value is used
      by the object to which it is assigned.


      --
      Bob Hairgrove
      NoSpamPlease@Ho me.com

      Comment

      Working...