For the memory allocation in class constructors, is it safe to use initializer list for simplifying the expression?

52 Views Asked by At

What is the correct syntax to do that? And what should I pay attention when practicing such technique.

1

There are 1 best solutions below

1
On

... correct syntax to do that?

 class Foo {
     Bar* bar_;
 public:
     Foo() : bar_(new Bar()) {}
 };

And what should I pay attention when practicing such technique.

You should ensure to call delete appropriately

      ~Foo() { delete bar_; }

The better way though is to use a smart pointer:

 class Foo {
     std::unique_ptr<Bar> bar_;
 public:
     Foo() : bar_(std::make_unique<Bar>()) {}
 };