As title.
I mean when I key in like following codes:
- string *c=static_cast<string*> (operator new[](3*sizeof(string)));
-
*c="test"; //error
-
I now know that string objects cannot be modified unless they have been initialized,
but I want to know the reason.
Is that only string object has this rule? or...?
When I wrote another class which is defined by myself:
- class test{
-
public:
-
test(const char*):_data(0){ cout << _data;};
-
private:
-
int _data;
-
};
-
int main()
-
{
-
test *c=static_cast<test*> (operator new[](3*sizeof(test)));
-
c[0]="test";
-
return 0;
-
}
-
// output: 0
-
Which means that test c did initialize, but why string couldn't?
It is because you are using new incorrectly. Your first code snippet should read
- string *c=new string();
-
*c="test"; //error
-
The way you use it, you never call the constructor, when means that the memory for the object is in an indeterminate state and random things will happen.
The reason why the other snippet worked is due to the data it holds.
Where in the world did you get the idea of 3*sizeof(type) from anyway? And where did you get the syntax of how to use operator new from?
You really should look at reading a good C++ book. I found “Thinking in C++” by Bruce Eckel fairly good, though I don’t know where you are starting from, so it may be good for you or it may be over your head, I dunno. It is a free book though, just search for it on the web.
Adrian