linux-c-programming.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: a.biardi@tiscali.it
To: linux-c-programming@vger.kernel.org
Subject: C++ temporaries
Date: Wed, 19 Jan 2005 21:56:00 +0100	[thread overview]
Message-ID: <200501192156.00928.a.biardi@tiscali.it> (raw)


Hi all,

I have a function similar to the following, which returns a string:

  std::string foo() {
    return <whatever>;
  }

..then I want to use its c_str(), say like this (sorry for the silly 
example):

  int main() {
    printf("foo is %s",foo().c_str());
  }

Of course, for printf() to work, the temporary object that is returned 
by foo() should not be (automatically) destroyed too early, or the 
pointer returned by c_str() would not be valid anymore.

So, my question is: *when* is that temporary string created and 
destroyed? is it safe to assume that it exists until printf() 
returns, and thus that I can use its c_str() this way?

I've always thought that the temporary would be destroyed *before* 
calling printf() [ create a string, get the value for c_str(), 
destroy the string, invoke printf() ] thus actually passing an 
invalid pointer in this case, but to my surprise I put together some 
lines and gcc proved me wrong. Is it just gcc? Or is it a standard 
C++ behavior?

Thanks,
Andrea.

             reply	other threads:[~2005-01-19 20:56 UTC|newest]

Thread overview: 2+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2005-01-19 20:56 a.biardi [this message]
2005-01-20  3:49 ` C++ temporaries Benjamin Sobotta

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=200501192156.00928.a.biardi@tiscali.it \
    --to=a.biardi@tiscali.it \
    --cc=linux-c-programming@vger.kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).