I’m trying to write c++ code without using the keywords new and delete.
First, is it a good practice or not ?
One of the side effects of coding like this is that I can’t rely on nullptrfor empty values.
For instance:
std::array<std::array<fb::Block *, Panel::Y>, Panel::X> blocks;
becomes
std::array<std::array<fb::Block, Panel::Y>, Panel::X> blocks;
What is the best way to describe an empty Block ?
I though about using this:
class Block {
private:
protected:
public:
...
static const Block EMPTY;
};
}
const Block EMPTY(0, BlockType::TUTORIAL, 0, 0);
What do you guys think ? Is this a good approach ?
If you want to write safe code and simplify memory management, you should indeed avoid the
delete. But there is no need to discard thenew. The best way to go is to allocate any object you want withnewand store it in smart pointers likestd::shared_ptrorstd::unique_ptr. You can always compare those pointers withnullptr. And all objects will be automatically deleted.Some will advise to replace raw
newwithmake_sharedandmake_uniquecalls in this scenario.The related question is when to use
T&and when to useT*for passing an argument to a function. The rule of thumb is: useT*whenever an input argument can be absent, useT&to ensure an input argument is provided.