How to choose where to store an object in C ++?

Possible duplicate
Proper stack and heap usage in C ++?

I'm starting to learn C ++ from the Java background, and one big difference is that I am no longer forced to:

  • dynamically allocates memory for objects
  • always use pointers to handle objects

as is the case in Java. But am I confused when I have to do what you can advise?

Currently, I am tempted to start whatever I like in Java, for example

Thing *thing = new Thing();
thing->whatever();
// etc etc
+3
source share
4 answers

Do not use pointers unless you know why you need them. If you need an object only for a while, select it on the stack:

Object object;
object.Method();

, :

int doStuff( Object& object )
{
    object.Method();
    return 0;
}

,

  • , , " " - .

, , , , , ++ . , std:: auto_ptr boost:: shared_ptr.

+5

. , , , . shared_ptr .

shared_ptr<Thing> thing( new Thing() );
thing->whatever();

. , , .

Thing thing;
thing.whatever();

, , ; -)

+3

, , , , .

++ , , , . ( RAII) , , - , GC Java, , (.. , ).

, , share_ptr, . , shared_ptr .

+1

, , - , ( ):

 Animal* animal = 0;
 if (rand() % 2 == 0)
    animal = new Dog("Lassie");
 else
    animal = new Monkey("Cheetah");

, , - , , ( , ). - , , ( ).

, shared_ptr unique_ptr ( ), .

+1

Source: https://habr.com/ru/post/1717243/


All Articles