Jim Langston wrote:
"Greg" <gr****@pacbell.net> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com... Jim Langston wrote: "Marcelo Pinto" <mp******@gmail.com> wrote in message
news:11*********************@g44g2000cwa.googlegro ups.com...
> Hi,
>
> Consider the following code snipet:
>
>
> void f(const std::string & msg)
> {
> //...
> for (...)
> {
> //...
> std::string msg = msg + " " + another_string; //1
This is legal. This msg local to the for loop hides the msg parameter.
So
it basically becomes:
std::string msg = "" + " " + another_string;
which is probably why you're asking.
No, there are generally no compiler warnings for hiding variables.
Although
there generally are for hiding methods in classes.
The local "msg" variable is accessed before it has been initialized
(because it is used in its own initializer.) Since the value of the msg
variable is indeterminate before its initialization, the outome of this
expression, though legal, is undefined.
Greg
Actually, I was reading somewhere that
std::string msg("Hello");
is more effecient than
std::string msg = "Hello";
Because one uses the regular constructor, one uses the assignment
constructor.
If the assignment constructor is uses, isn't the default constructor called
first? Or am I mistaken on that?
No, an object's constructor is not called before an object is
initialized with itself. For example, compiling and running this
program:
#include <string>
int main()
{
std::string s = s + "hello";
}
terminates with a segmentation fault on my machine. It crashes because
the program is accessing s's storage as if it were a constructed
std::string. Although the Standard does not require that any warning be
issued, gcc does have a special switch, -Winit-self, to check for this
kind of mistake (though I can't imagine it is all that common). But it
is not entirely straightforward, since enabling the warning requires
that two other switches also be set.
Actually these declarations:
std::string msg("Hello");
std::string msg = "Hello";
are equivalent. Both call the same constructor. The use of the "=" in
one is confusing since it looks very much like last line in this
sequence:
std::string msg;
msg = "Hello";
In this case, there is a call to the std::string's assignment operator
because msg has already been constructed. In general, the rule-of-thumb
is to prefer construction over assignment (as in a loop for example)
since construction is usually more efficient. I'm not sure whether that
is the case with std::string, though I can't think of any reason why it
would not be.
Greg