lifetime of char[]?

S

Stefan Ram

In the following example:

{ const char * concat =( stdstring + stdstring_ ).c_str(); ... }

it seems that the value of c_str() is a pointer to a
temporary char array. Now, that POINTER is used to
initialize the variable »concat«.

There might be a rule that a temporary can be used to
initialize an object with automatic storage duration, and
then the lifetime of that temporary is extended to the
lifetime of that automatic object.

But what about the temporary char ARRAY pointed to by the
pointer »concat«? Is there a rule that extends its lifetime
too? After all, it is not the same as the POINTER to it,
so another rule would be needed to extend its lifetime too.

So, can »concat« safely (portably) be dereferenced in this
block to get access to the concatenation of the C++-strings
as a C-string?
 
M

Melzzzzz

On 9 Nov 2013 01:18:25 GMT
In the following example:

{ const char * concat =( stdstring + stdstring_ ).c_str(); ... }


So, can »concat« safely (portably) be dereferenced in this
block to get access to the concatenation of the C++-strings
as a C-string?

No.
 
Ö

Öö Tiib

In the following example:

{ const char * concat =( stdstring + stdstring_ ).c_str(); ... }

it seems that the value of c_str() is a pointer to a
temporary char array. Now, that POINTER is used to
initialize the variable »concat«.

Yes, and pointlessly so. Smart enough tool could warn. It is
useless pointer on very next line. That works:

{
std::string& ref =( stdstring + stdstring_ );
const char* concat = ref.c_str();
// ...
} // <- ref is valid until here and so is concat

But generally ... avoid raw pointers.
 
A

Alf P. Steinbach

Yes, and pointlessly so. Smart enough tool could warn. It is
useless pointer on very next line. That works:

{
std::string& ref =( stdstring + stdstring_ );
const char* concat = ref.c_str();
// ...
} // <- ref is valid until here and so is concat

But generally ... avoid raw pointers.

The above won't compile.

But

"std::string const&"

or

"std::string&&"

would.

The easiest and safest solution is to store the concatenation result in
a std::string, since that's the string class used in the code.


Cheers,

- Alf (nitpicking)
 
Ö

Öö Tiib

That is wrong Mr Homophobic Bigot; it needs to be reference to const.

Thanks for correcting, Mr Foulmouthed Fagot, that was a typo. OP
needed const but I mistyped it somehow.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top