What's the scope of a variable defined in parameter list?

M

Meal

Is this safe?

foo(C2X(""));

C2X is a macro defined as
#define C2X(str) XStr(str).unicodeForm()

XStr is a kind of string processing class.
unicodeForm() returns pointer of its member string.

When the caller calls foo(C2X("")), a temporary variable XStr(str) is
created, and returns the pointer of its member string as foo's
parameter.
1) Inside of foo, is the pointer still valid?
2) After calling foo, is the pointer still valid?

On VC2003, 1) is valid and 2) is invalid, but I don't know if C++
standard says the same.
 
V

Victor Bazarov

Meal said:
Is this safe?

foo(C2X(""));

What do you mean by "safe"?
C2X is a macro defined as
#define C2X(str) XStr(str).unicodeForm()

XStr is a kind of string processing class.
unicodeForm() returns pointer of its member string.

When the caller calls foo(C2X("")), a temporary variable XStr(str) is
created, and returns the pointer of its member string as foo's
parameter.
1) Inside of foo, is the pointer still valid?
Yes.

2) After calling foo, is the pointer still valid?

Not for long.
On VC2003, 1) is valid and 2) is invalid, but I don't know if C++
standard says the same.

The temporary object created by 'XStr("")' has the lifetime the same as
the evaluation of the complete expression where it's created. In your
case, it's until 'foo' returns and the result of calling it is discarded.
The expression statement ends in the semicolon. After 'foo' returns
but before the next statment begins executing the temporary is destroyed.

V
 

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,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top