智能指针(unique_ptr)而不是原始指针作为类成员

vla*_*don 1 c++ pointers memory-leaks unique-ptr c++11

给定一个类层次结构:

class A {

private:
  string * p_str;

public:
  A() : p_str(new string())
  {
  }

  virtual ~A() {
    delete p_str;
  }
};

class B : public A {
public:
  B() {
  }

  virtual ~B() override {
  }

  virtual void Test() {
    cout << "B::Test()" << endl;
  }
};

int main(int, char**)
{
  B b;

  b.Test();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有一个p_str指向字符串的指针(无论它指向什么对象).

std::unique_ptr除非没有写作,否则有什么优势可以替换它delete p_str

class A {

private:
  std::unique_ptr<string> p_str;

public:
  A() : p_str(make_unique<string>())
  virtual ~A() {}

}
Run Code Online (Sandbox Code Playgroud)

?如果任何派生类的构造函数抛出异常,则在任何代码变体中都会发生内存泄漏.

UPD我试过这段代码:

包括

#include <memory>
using namespace std;

class Pointed {
public:
  Pointed() { std::cout << "Pointed()\n"; }
  ~Pointed() { std::cout << "~Pointed()\n"; }
};

class A1 {
private:
  Pointed * p_str;

public:
  A1() : p_str(new Pointed()) {
    cout << "A1()\n";
    throw "A1 constructor";
  }

  virtual ~A1() {
    cout << "~A1()\n";
    delete p_str;
  }
};

class B1 : public A1 {
public:
  B1() {
    throw "B constructor";
  }

  virtual ~B1() override {
    cout << "~B1()\n";
  }

  virtual void Test() {
    cout << "B1::Test()" << endl;
  }
};

class A2 {
private:
  std::unique_ptr<Pointed> p_str;

public:
  A2() : p_str(make_unique<Pointed>()) {
    cout << "A2()\n";
    throw "A2 constructor";
  }

  virtual ~A2() {
    cout << "~A2()\n";
  }
};


class B2 : public A2 {
public:
  B2() {
    cout << "B2()\n";
    throw "B2 constructor";
  }

  virtual ~B2() override {
    cout << "~B2()\n";
  }

  virtual void Test() {
    cout << "B2::Test()" << endl;
  }
};

int main(int, char**) {
  cout << "B1::A1 (raw pointers)\n";

  try {
    B1 b1;
  }
  catch (...) {
    cout << "Exception thrown for B1\n";
  }

  cout << "\nB2::A2 (unique pointers)\n";

  try {
    B2 b2;
  }
  catch (...) {
    cout << "Exception thrown for b2\n";
  }

  cin.get();

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

B1::A1 (raw pointers)
Pointed()
A1()
Exception thrown for B1

B2::A2 (unique pointers)
Pointed()
A2()
~Pointed()
Exception thrown for b2
Run Code Online (Sandbox Code Playgroud)

因此,结果是unique_ptr在声明成员的同一类的构造函数中发生异常时自动删除.

For*_*veR 7

使用原始指针,您可以进行双重删除,因为您没有手动实现的复制c-tor和赋值运算符.

A a;
A b = a; // b.p_str store the same address, that a.p_str
Run Code Online (Sandbox Code Playgroud)

随着unique_ptr您不能复制/分配的对象,但你可以移动,而无需编写移动C-TOR /移动赋值运算符.

A a;
A b = a; // cannot do this, since `unique_ptr` has no copy constructor.
A b = std::move(a); // all is okay, now `b` stores `unique_ptr` with data and `a` stores `nullptr`
Run Code Online (Sandbox Code Playgroud)

但实际上,我不知道,为什么你应该在这里存储指针,而不仅仅是类型的对象std::string,它是你的例子中的最佳解决方案.