c++ - Why is a pointer needed for initialising an object on the heap, but not on the stack? -


for example in these 2 codes, 1 requires no pointer, other does. why this? if myobject1 isn't pointer, exactly?

class object{ … };   int main(){     // create instance on stack     object myobject1;      // create instance on heap     object *myobject2 = new object;      return 0; } 

thanks help.

both of declarations definitions of objects have automatic storage duration. is, both destroyed @ end of function. first 1 declaring object type object , second object* type object.

it happens initializer myobject2 new-expression. new expression dynamically allocates object , returns pointer it. myobject2 being initialized pointer dynamically allocated object.

so witnessing 2 different ways of creating objects. 1 variable definition , 1 new-expression.

it doesn't make sense other way. imagine new-expression didn't return pointer object referred object directly. might write so:

object myobject2 = new object(); 

however, c++ works value semantics default. means dynamically allocated object copied myobject2 , you've lost track of it. don't have way address of object more. new-expression returns pointer have handle dynamically allocated object.

you might say, "well that's how i'd write in java!" that's because java works in different way. in java, myobject2 reference setting point new object object. doesn't copy object in way.

c++ doesn't require have use pointer when dynamically allocate object. in fact, (which kind of java equivalent):

object& myobject2 = *(new object()); 

but that's bad idea. masks fact object dynamically allocated , easy make mistake , forget destroy object (which don't have care in java). @ least pointer might remind so. however, can lead buggy or unclear code, why recommended use smart pointer when possible.

so in short: that's how new-expression behaves. dynamically allocates object , returns pointer it.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -