When to use pointers and when not to?

后端 未结 5 1292
滥情空心
滥情空心 2020-12-02 08:21

I\'m used to doing Java programming, where you never really have to think about pointers when programming. However, at the moment I\'m writing a program in C++. When making

5条回答
  •  情书的邮戳
    2020-12-02 08:40

    In the first example memory for the Bar object will be allocated automatically when you construct the Foo object. In the second case you need to allocate the memory yourself. So you must call:

    Foo *foo = new Foo();
    foo->b = new Bar();
    

    This may be desirable if the Bar object is large and you don't want to bundle it with the Foo object. It is also desirable when the construction of the Bar object is independent of the creation of Foo object. In this case the b object is "injected" into foo:

    Foo *foo = new Foo();
    foo->b = b_ptr;
    

    where b_ptr is constructed somewhere else and a pointer is passed to foo.

    For smaller objects it is dangerous, as you may forget to allocate the memory.

提交回复
热议问题