为什么使用'new'会导致内存泄漏?

  • 回答 (2)
  • 关注 (0)
  • 查看 (16)

首先学习了C#,现在开始使用C ++。据我所知,C ++中的new运算符与C#中的运算符不相似。

能解释这个示例代码存在的问题吗:

class A { ... };
struct B { ... };

A *object1 = new A();
B object2 = *(new B());
叶风叶风提问于
我贼迷美丽策回答于
已采纳

new T()正在创建一个类型为T带着动态存储持续时间

需要传递一个指向它的指针delete

需要一个新的对象:

A a; // a new object of type A
B b; // a new object of type B

如果确实需要动态存储持续时间,请将指向分配对象的指针存储在自动删除该对象的自动存储持续时间对象中:

template <typename T>
class automatic_pointer {
public:
    automatic_pointer(T* pointer) : pointer(pointer) {}

    // destructor: gets called upon cleanup
    // in this case, we want to use delete
    ~automatic_pointer() { delete pointer; }

    // emulate pointers!
    // with this we can write *p
    T& operator*() const { return *pointer; }
    // and with this we can write p->f()
    T* operator->() const { return pointer; }

private:
    T* pointer;

    // for this example, I'll just forbid copies
    // a smarter class could deal with this some other way
    automatic_pointer(automatic_pointer const&);
    automatic_pointer& operator=(automatic_pointer const&);
};

automatic_pointer<A> a(new A()); // acts like a pointer, but deletes automatically
automatic_pointer<B> b(new B()); // acts like a pointer, but deletes automatically

小川医学生回答于

可以尝试下使用:

// creates a new object on the heap:
new B()
// dereferences the object
*(new B())
// calls the copy constructor of B on the object
B object2 = *(new B());

另一个样本是:

A *object1 = new A();

delete分配的内存:

delete object1;

扫码关注云+社区