简体   繁体   English

C ++新建和删除ptr包装器类

[英]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. 有人问什么是C ++包装器类,我想他提供了一个很好的答案。 His username: GManNickG from Stack Overflow provided the following code with his answer: 他的用户名:来自Stack Overflow的GManNickG提供了以下代码并给出了答案:

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. 我从几个不同的人那里听说,使用new和delete关键字被认为是不好的做法。 Is there a certain situation in which I should use new or delete? 在某些情况下,我应该使用new还是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 . (几乎)总是有比使用new更好的方法。 There is absolutely always a better way than using delete . 绝对总有比使用delete更好的方法。

Have a look at the documentation for std::shared_ptr<> and std::unique_ptr<> . 看看std::shared_ptr<>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. c ++标准已经为您完成了。 There is no good argument to reinvent that particular wheel. 没有很好的论据来重新发明那个特定的轮子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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