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 point string, or may null/nullptr, or may point random location in memory. therefore, should use plain old string's on string*'s wherever possible using them less prone errors.

  • declaring string object places on stack, meaning automatically cleaned when leaves scope. using new 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

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -