when should I use the new operator in C++

后端 未结 9 1999
有刺的猬
有刺的猬 2020-12-21 11:47

Say I have a class called Money which has parameters Dollars and Cents

I could initialize it in the followings 2 ways:

9条回答
  •  情书的邮戳
    2020-12-21 12:23

    Money a(3,15);
    

    Allocates an Money object in the local scope.

    Money* b=new Money(3,15);
    

    Allocates a pointer-variable to the local scope, and makes the pointer "point" to a Money object that resides in the free store (assuming the allocation completed successfully, otherwise an std::bad_alloc() is thrown)

    Example 1 :

    Assume next scenario:

    Money * b = initialize();
    

    where

    Money* initialize()
    {
          Money x(2 , 15);
          return &x;
    }
    

    This will fail because after initialize() reaches the end of execution x is destroyed, and now b points to a location that is invalid to use and invokes Undefined Behaviour if you do used it. so instead you should allocate it with a pointer

    Money* initialize()
    {
          return new Money(2,15);
    }
    

    The free-store is also used when you want to store and use arrays of great size.

    There is a difference between the two as you noticed on the example, and that is that in the local scope x you do not need to delete the object. But when using new you will have to manually do a delete x;. Otherwise a memory leak (memory space is occupied without ever going to be used again, hence eating memory) is occurring.

    See Martin York's answer for deeper knowledge beyond this post.

提交回复
热议问题