C++ Object Instantiation

后端 未结 9 1950
孤街浪徒
孤街浪徒 2020-11-30 16:36

I\'m a C programmer trying to understand C++. Many tutorials demonstrate object instantiation using a snippet such as:

Dog* sparky = new Dog();
相关标签:
9条回答
  • 2020-11-30 17:08

    There's no reason to new (on the heap) when you can allocate on the stack (unless for some reason you've got a small stack and want to use the heap.

    You might want to consider using a shared_ptr (or one of its variants) from the standard library if you do want to allocate on the heap. That'll handle doing the delete for you once all references to the shared_ptr have gone out of existance.

    0 讨论(0)
  • 2020-11-30 17:09

    I've seen this anti-pattern from people who don't quite get the & address-of operator. If they need to call a function with a pointer, they'll always allocate on the heap so they get a pointer.

    void FeedTheDog(Dog* hungryDog);
    
    Dog* badDog = new Dog;
    FeedTheDog(badDog);
    delete badDog;
    
    Dog goodDog;
    FeedTheDog(&goodDog);
    
    0 讨论(0)
  • 2020-11-30 17:10

    The only reason I'd worry about is that Dog is now allocated on the stack, rather than the heap. So if Dog is megabytes in size, you may have a problem,

    If you do need to go the new/delete route, be wary of exceptions. And because of this you should use auto_ptr or one of the boost smart pointer types to manage the object lifetime.

    0 讨论(0)
提交回复
热议问题