简体   繁体   中英

C++ new and delete ptr wrapper class

There was a question asked about what a C++ wrapper class is, and I think he provided a good answer. His username: GManNickG from Stack Overflow provided the following code with his answer:

class int_ptr_wrapper
{
public:
    int_ptr_wrapper(int value = 0) :
    mInt(new int(value))
    {}

    // note! needs copy-constructor and copy-assignment operator!

    ~int_ptr_wrapper()
    {
        delete mInt;
    }

private:
    int* mInt;
};

That code prompted me with a question. I've heard from several different people that its considered bad practice to use the new and delete keywords. Is there a certain situation in which I should use new or delete? Also If I wrote the code above like below, which is considered better practice?

class int_ptr_wrapper
{
public:
    int_ptr_wrapper(int value = 0) :
        m_int(&value) {}
private:
    int* m_int;
};

There is (almost) always a better way than using new . There is absolutely always a better way than using delete .

Have a look at the documentation for std::shared_ptr<> and std::unique_ptr<> . Between them they cover every scenario you will ever need with regard to scoped memory management, automatic releasing of memory resources, automatic closing of files, automatic zeroing out of memory used for encryption... and so on. This is because both classes give you the opportunity to provide a custom deleter, so no matter how complex your memory deallocation needs, they're covered flawlessly and safely.

Writing a complete scoped memory manager class is harder than it at first seems. The c++ standard has done it for you. There is no good argument to reinvent that particular wheel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM