Default Copy Ctor

G

giles

Below code when run causes a crash. why?

#include <string>

using namespace std;

int main()
{
string name = 0;
return 0;
}

TIA,
Giles
 
R

Rolf Magnus

giles said:
Below code when run causes a crash. why?

#include <string>

using namespace std;

int main()
{
string name = 0;

This is equivalent to:

string name(string((const char*)0);

And the behavior is undefined if you provide a null pointer as argument to
the constructor that takes a const char*. If you want an empty string, just
write:

string name;
 
U

ulrich

Below code when run causes a crash. why?

#include <string>

using namespace std;

int main()
{
string name = 0;
return 0;
}

you are assigning a number to a string.

possibly, what you wanted to do is string name = "";
still, this is superfluous, because a string object is empty by default.

if you want to know exactly what's going on, step into it with your
debugger...
 
R

Ron Natalie

ulrich said:
you are assigning a number to a string.
Nope: You're not assigning anything, this is
initialization syntax. Further, there is no conversion
of a number to string. What exists is a converting constructor
of type const char*, which this null pointer constant matches.
However that value yields undefined behavior when used to initialize
a string.
 

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,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top