pointers - C++ new and delete ptr wrapper class -
there question asked c++ wrapper class is, , think provided answer. username: gmannickg stack overflow provided following code answer:
class int_ptr_wrapper { public: int_ptr_wrapper(int value = 0) : mint(new int(value)) {} // note! needs copy-constructor , copy-assignment operator! ~int_ptr_wrapper() { delete mint; } private: int* mint; };
that code prompted me question. i've heard several different people considered bad practice use new , delete keywords. there situation in should use new or delete? if wrote code above below, considered better practice?
class int_ptr_wrapper { public: int_ptr_wrapper(int value = 0) : m_int(&value) {} private: int* m_int; };
there (almost) better way using new
. there absolutely better way using delete
.
have @ documentation std::shared_ptr<>
, std::unique_ptr<>
. between them cover every scenario ever need regard scoped memory management, automatic releasing of memory resources, automatic closing of files, automatic zeroing out of memory used encryption... , on. because both classes give opportunity provide custom deleter, no matter how complex memory deallocation needs, they're covered flawlessly , safely.
writing complete scoped memory manager class harder @ first seems. c++ standard has done you. there no argument reinvent particular wheel.
Comments
Post a Comment