c++ - Difference between following declarations -
recent times confused use of new keyword string data type. can please try clarify it
what's difference between following string initialization:
1)
string* name = new string("abc") ; .... delete name;
2)
string name = "abc";
is advisable use new keyword , values within string how stored in heap internal buffers of std::string
. if explains storage location.
what's difference between returning string vs string*
string* name() { string* name = new string("abc") ; return name; } string name() { string name = "abc"; return name; }
there several reasons prefer second approach on first:
most important reason:
string
string
, period.string*
may pointstring
, or maynull
/nullptr
, or may point random location in memory. therefore, should use plain oldstring
's onstring*
's wherever possible using them less prone errors.declaring
string
object places on stack, meaning automatically cleaned when leaves scope. usingnew
means have manually clean allocated memory.new
relatively slow operation. using stack variables faster.
while string
store's data on heap, allocating string
on heap still adds level of indirection.
Comments
Post a Comment