First of all, when you use new
you need to use delete
, not free()
. In fact, you should really never use free()
or malloc()
in C++. A good explanation for why you should never mix new
and free
or malloc()
and delete is that new
and delete
call the constructor and destructor, free()
and malloc()
have nothing to do with that, they just allocate and deallocate memory, especially for built in classes this is bad because you don't know what is supposed to happen in std::string
's destructor or constructor, it might be possible to make it work with your own built in class (but don't do it).
You can replace your code with this:
string * p = new string[8];
cout<<sizeof(p)<<endl;
delete [] p;
In the end, I would suggest you use a built in data type like std::vector
or std::array
. They are much more C++-ish than a standard old C array.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…