Does using references instead of pointers, resolve memory leaks in C++?

后端 未结 5 1811
花落未央
花落未央 2020-12-11 16:10

Most of memory leaks appear when a pointer of an object returned and programmer forgot to delete it.

for example:

class my_class
{
  ...
};

my_class         


        
5条回答
  •  轮回少年
    2020-12-11 17:04

    You shouldn't replace an owning pointer (one that is responsible for deletion) with a reference; it's idiomatic to assume that references never, ever own the referred resource.

    my_class& func1()
    {
        my_class* c = new my_class;
        return *c;
    }
    
    int main()
    {
        my_class& ref = func1();
        // MUST delete, but this is ugly!
        delete &ref;
    }
    

    Instead, replace owning pointers by smart pointers: std::unique_ptr func1() { return std::unique_ptr(new my_class); }

    int main()
    {
        auto p = func1();
        // You gain exception-safety for free
    }
    

    You are correct that non-owning pointers can be replaced by references. It is recommended for most cases (see the link at end for more information).

    // Won't have to check for 0 in the body
    void
    my_func1(my_class&);
    
    std::unique_ptr
    func1()
    {
        return std::unique_ptr(new my_class);
    }
    
    int main()
    {
        auto p = func1();
    
        func2(*p);
    }
    

    Here is a question regarding the difference of uses between raw pointers and smart pointers. In an answer of mine I mention difference use cases for raw pointers vs references.

提交回复
热议问题