C ++智能指针会影响内存泄漏问题

时间:2018-03-05 07:24:45

标签: c++ c++11 smart-pointers

我编写了一个简单的C ++程序来测试智能指针,但我发现智能指针会影响内存泄漏问题。请参阅以下代码:

test.cpp :(已在CLANG 7.0或gcc 7.3.0中测试过它)

#include <bits/stdc++.h>

using namespace std;

class Date {
private:
  int day = 0, month = 0, year = 0;
  string dateInString;

public:
  Date() { cout << "Date Constructor:" << *this << endl; }

  Date(int inMonth, int inDay, int inYear)
    : day(inDay), month(inMonth), year(inYear)
  {
    cout << "Date Constructor: " << *this << ends;
    DisplayDate();
  }

  Date(const Date &copySource)
  {
    cout << "Date Copy Constructor." << *this << endl;
    day   = copySource.day;
    month = copySource.month;
    year  = copySource.year;
  }

  Date(Date &&moveSource)
  {
    cout << "Date Move Constructor." << *this << endl;
    day   = moveSource.day;
    month = moveSource.month;
    year  = moveSource.year;
  }

  virtual ~Date() { cout << "Date Destructor: " << *this << endl; }

  const Date &operator=(const Date &copySource)
  {
    cout << "Date Assignment Operator=" << *this << endl;
    if (this != &copySource) {
      day   = copySource.day;
      month = copySource.month;
      year  = copySource.year;
    }
    return *this;
  }

  operator const char *()
  {
    // assists string construction
    ostringstream formattedDate;
    formattedDate << month << "/" << day << "/" << year;
    dateInString = formattedDate.str();
    return dateInString.c_str();
  }

  void DisplayDate() { cout << month << "/" << day << "/" << year << endl; }

  // prefix increment
  Date &operator++()
  {
    ++day;
    return *this;
  }

  // prefix decrement
  Date &operator--()
  {
    --day;
    return *this;
  }

  // postfix increment
  Date operator++(int postfix)
  {
    Date copy(month, day, year);
    ++day;
    // copy of instance increment returned
    return copy;
  }

  // postfix decrement
  Date operator--(int postfix)
  {
    cout << "operator--" << endl;
    auto p = make_unique<Date>(month, day, year);
    // auto p = new Date(month, day, year);
    --day;
    // copy of instance increment returned
    return *p;
  }
};

auto main() -> decltype(0)
{
  Date holiday(12, 25, 2016);

  Date postfixDay1;
  postfixDay1 = holiday--;
  cout << "holiday after a postfix-decrement is : ";
  holiday.DisplayDate();

  cout << "postfixDay1 after a postfix-decrement is : ";
  postfixDay1.DisplayDate();

  return 0;
}

程序将输出以下信息:

Date Constructor: 12/25/2016 12/25/2016
Date Constructor:0/0/0
operator--
Date Constructor: 12/25/2016 12/25/2016
Date Copy Constructor.0/0/0
Date Destructor: 12/25/2016
Date Assignment Operator=0/0/0
Date Destructor: 12/25/2016
holiday after a postfix-decrement is : 12/24/2016
postfixDay1 after a postfix-decrement is : 12/25/2016
Date Destructor: 12/25/2016
Date Destructor: 12/24/2016

要点: 我们可以发现调用了三个构造函数,但是调用了四个析构函数!这意味着智能指针已被解构两次。

为什么智能指针无法处理这种情况?

0 个答案:

没有答案