C++ Object Instantiation

后端 未结 9 1961
孤街浪徒
孤街浪徒 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: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);
    

提交回复
热议问题