Is it considered bad manners/bad practice to explicitly place object members on the heap (via new)? I would think you might want to allow the client to choose the memory region to instantiate the object. I know there might be a situation where heap members might be acceptable. If you know a situation could you describe it please?
Is it considered bad manners/bad practice to explicitly place object members on the heap
Share
If you have a class that’s designed for copy semantics and you’re allocating/deallocating a bunch of memory unnecessarily, I could see this being bad practice. In general, though, it’s not. There are a lot of classes that can make use of heap storage. Just make sure you’re free of memory leaks (deallocate things in the destructor, reference count, etc.) and you’re fine.
If you want more flexibility, consider letting your user specify an Allocator. I’ll explain.
Certain classes, e.g.
std::vector, string, map, etc. need heap storage for the data structures they represent. It’s not considered bad manners; when you have an automatically allocatedvector, the user is expected to know that a buffer is allocated when thevectorconstructor gets called:Likewise, for
std::string, you know there’s an internal, heap-allocatedchar*. Whether there’s one perstringinstance is usually up to the STL implementation; often times they’re reference counted.However, for nearly all of the STL classes, users do have a choice of where things are put, in that they can specify an allocator.
vectoris defined kind of like this:Internally,
vectorusesAlloc(which defaults to whatever the default allocator is for T) to allocate the buffer and other heap storage it may need. If users doesn’t like the default allocation strategy, they can specify one of their own:Now when the constructor allocates, it will use a
MyCustomAllocatorinstead of the default. Here are some details on writing your own STL allocator.If you’re worried that it might be ‘bad manners’ to use the heap for certain storage in your class, you might want to consider giving users of your class an option like this so that they can specify how things are to be allocated if your default strategy doesn’t fit their needs.