str().c_str() question

M

ma740988

Consider:

bool transmit ( const char* pch, size_t len )
{
int const val = strcmp( pch, "who_am_i" );
if ( val == 0 )
return ( true );
return ( false );
}

int main ( void )
{
std::stringstream str;
str << "who_am_i";
size_t const sz = str.str().size() ; // the temporary created is
destroyed
char* ftest = new char [ sz + 1 ];
strcpy( ftest, str.str().c_str() );
std::cout << std::hex
<< static_cast<int>(ftest[0])
<< ""
<< static_cast<int>(ftest[1])
<< std::endl;

if ( transmit ( str.str().c_str(), str.str().size()) )
{ std::cout << " success " << std::endl; }
else
{ std::cout << " failure " << std::endl; }

}

At issue:
str.str().c_str().

If I did:
const char* ptr_me = str.str().c_str();

The temporary returned from .str() is destroyed at the end of the full
expression, and it takes the buffer used by .c_str() with it. Not
good.

The question then becomes, where's the end of the full expression for
the case where I call the transmit function. Is that at the
terminating brace of the transmit function?
In my mind the temporary should be destroyed at the opening brace of
transmit but that doesn't appear to be the case.
 
V

Victor Bazarov

ma740988 said:
Consider:

bool transmit ( const char* pch, size_t len )
{
[..]
return ( false );

You really don't need parentheses here, you know that, right?
}

int main ( void )

'void' is also superfluous. All those things just make your code
a bit less readable.
{
std::stringstream str;
[...]
if ( transmit ( str.str().c_str(), str.str().size()) )
.. ^_______________________________________________^
.. This is your "full expression"
{ std::cout << " success " << std::endl; }
else
{ std::cout << " failure " << std::endl; }

}

At issue:
str.str().c_str().

If I did:
const char* ptr_me = str.str().c_str();

The temporary returned from .str() is destroyed at the end of the
full expression, and it takes the buffer used by .c_str() with it.
Not good.

The question then becomes, where's the end of the full expression for
the case where I call the transmit function. Is that at the
terminating brace of the transmit function?
In my mind the temporary should be destroyed at the opening brace of
transmit but that doesn't appear to be the case.

The function call is part of the full expression. The full expression
is bound on the right by the closing parenthesis of the 'if' statement.

V
 
M

ma740988

Victor said:
ma740988 wrote: [..]


The function call is part of the full expression. The full expression
is bound on the right by the closing parenthesis of the 'if' statement.
Thanks Vic
 

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

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top