C++_day06_运算符重载_智能指针

1.只有函数运算符可以带缺省函数,其他运算符函数主要由操作符个数确定

2.解引用运算符和指针运算符

示例代码:

#include <iostream>
using namespace std; class A{
public:
A(int data = ):m_data(data)
  {
    cout << "A构造" << endl;
  }

  ~A(void)
  {
    cout << "A析构" << endl;
  }int m_data;

private:

};

class PA{
public:
PA (A* pa = NULL):m_pa(pa){}
 

   ~PA(void)
   {
     if(m_pa)
      {
      delete m_pa;
      m_pa = NULL;
      }
    }

    A& operator*(void) const
{
return *m_pa;
}
A* operator->(void) const
{
return &**this;  //this是指向对象pa的指针,*this是pa,**this是复用上面解引用的运算符。
} private:
A* m_pa; }; int main(void)
{
/*
A* pa = new A(1234);
(*pa).m_data = 5678;
cout << pa->m_data << endl;
delete pa;
*/
PA pa(new A());
(*pa).m_data = ;
//pa.operator*().m_data = 5678;
cout << (*pa).m_data << endl;
cout << pa->m_data << endl;
//cout << pa.operator->()->m_data << endl; return ;
}

3.智能指针无需手动释放

#include <iostream>
#include <memory> using namespace std; class Student{
public:
Student (string const& name, int age):m_name(name), m_age(age)
{
cout << "Student构造" << endl;
}
~Student(void)
{
cout << "Student析构" << endl;
}
string m_name;
int m_age;
}; void foo(void)
{
auto_ptr<Student> ps(new Student("张无忌", ));
cout << (*ps).m_name << ", " << ps->m_age << endl;
} int main(void)
{
for(int i = ; i < ; i++)
foo();
return ;
}

运行结果:

C++_day06_运算符重载_智能指针

C++_day06_运算符重载_智能指针

智能指针其实是做指针的转移,

C++_day06_运算符重载_智能指针

1.智能指针没有复制语义,只有转移语义。

2.不能用智能指针管理对象数组。

C++_day06_运算符重载_智能指针

上一篇:BZOJ_1797_[Ahoi2009]Mincut 最小割_最小割+tarjan


下一篇:elasticsearch-权威指南笔记-基础部分