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"};
}
Lumpi
  • 98
  • 1
  • 9
  • 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`) is preferable to a raw pointer (`Submarine *`) . – Peter May 06 '21 at 07: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. – Jarod42 May 06 '21 at 09:51

1 Answers1

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.

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52