0

Is the use of new/delete appropriate here? Or any way to avoid them?

The point: class myOptions need an instance of Submarine. The Parameter are known at the time the myOptions-Construcor is called.

#include <iostream> #include <string> class Submarine { public: Submarine(std::string o) { std::cout << "create class Submarine: " << o << "\n"; } ~Submarine(){}; }; class myOptions { public: myOptions(std::string o):option(o) { std::cout << "create class myOption: " << option << "\n"; submarine = new Submarine(option); } ~myOptions() { delete submarine; } private: std::string option{}; Submarine *submarine; }; int main(void){ myOptions{"help"}; } 
2
  • 3
    For your example as shown, it is not necessary that myOptions contain a Submarine *. A Submarine will suffice. It is usually better to initialise members of a class (whether pointers or not) in the constructor initialiser list, not in the body of constructors. There are cases (e.g. Submarine is a polymorphic base) where a pointer is needed - but a smart pointer (like std::unique_ptr<Submarine>) is preferable to a raw pointer (Submarine *) . Commented May 6, 2021 at 7:55
  • "Is the use of new/delete appropriate here?" I would say that only valid case is when you implement your own smart pointers/allocators/containers. Else use existing smart pointer/containers. Commented May 6, 2021 at 9:51

1 Answer 1

4

You don't need to use dynamic memory here:

class myOptions { public: myOptions(std::string o):option(o), submarine(o) { std::cout << "create class myOption: " << option << "\n"; } private: std::string option{}; Submarine submarine; }; 

If you really need to use dynamic memory allocation (and you are not allowed to use smart pointers), you must apply the rule of five to your class. Currently it will blow up your program anytime you decide to pass it by value.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.