c++ - How to pass an object's address on the heap from a function using a pointer -


i'm trying create object on heap, pass it's address calling function, can't work!

if function called main, why can't store address of object in new pointer?

feline newfeline(int height, int weight) {   feline *myfeline = new feline(height, weight);   return *myfeline; }  int main() {   feline *f2;   *f2 = newfeline(10, 100);   //cout << f2->getheight() << endl;   return 0; } 

when run bus error: 10. oh , cats.

there multiple problems code.

first of all, newfeline function return temporary feline. , method has memory leak (the allocated feline not deallocated). normally, temporary disappear after statement called newfeline function.

second, filling in memory contents f2 pointing to. f2 not initialized, pointing random memory address. copying temporary feline memory address crash application.

to solve it, need change newfeline returns address of allocated feline, not copy of it, this:

feline *newfeline(int height, int weight) {    feline *myfeline = new feline(height, weight);    return myfeline; } 

second, let f2 point return value of newfeline, not change contents of f2, this:

feline *f2; f2 = newfeline(10, 100); 

better write on 1 line, this:

feline *f2 = newfeline(10, 100); 

or use c++11 auto keyword:

auto f2 = newfeline(10,100); 

to prevent memory leaks, it's better let newfeline return unique_ptr feline, this:

std::unique_ptr<feline> newfeline(int height, int weight) {    feline *myfeline = new feline(height, weight);    return myfeline; } 

that way, f2 (if using auto) become unique_ptr, , when f2 goes out of scope, allocated feline automatically deleted.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -