C++ 用智能指针这样包装 this 指针是否可行
#include <iostream>
#include <memory>
using namespace std;
class A;
class B
{
public:
B(shared_ptr<A> a)
{
pa = a;
cout << "B 构造..." << endl;
}
~B()
{
cout << "B 析构..." << endl;
}
shared_ptr<A> pa;
public:
void Hello()
{
cout << "hello I am B Obj." << endl;
}
};
class C
{
public:
C(shared_ptr<A> a)
{
pa = a;
cout << "C 构造..." << endl;
}
~C()
{
cout << "C 析构..." << endl;
}
shared_ptr<A> pa;
public:
void Hello()
{
cout << "hello I am C Obj." << endl;
}
};
class A
{
public:
A()
{
cout << "A 构造..." << endl;
self = shared_ptr<A>(this, [](A* a) { cout << "跳过 delete." << endl; });
pb = make_shared<B>(self);
pc = make_shared<C>(self);
}
~A()
{
cout << "A 析构..." << endl;
}
shared_ptr<B> pb;
shared_ptr<C> pc;
private:
shared_ptr<A> self;
public:
void Hello()
{
cout << "hello I am A Obj." << endl;
}
};
int main()
{
auto a = make_shared<A>();
a->pb->Hello();
a->pc->Hello();
a->pb->pa->Hello();
a->pc->pa->Hello();
system("pause");
return 0;
}
输出:
A 构造...
B 构造...
C 构造...
hello I am B Obj.
hello I am C Obj.
hello I am A Obj.
hello I am A Obj.
请按任意键继续. . .
A 析构...
C 析构...
B 析构...
跳过 delete.
.exe (进程 1940)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
多文件拆分
A.h
#pragma once
#include <memory>
#include "B.h"
#include "C.h"
class A
{
public:
A();
~A();
std::shared_ptr<B> pb;
std::shared_ptr<C> pc;
void Hello();
private:
std::shared_ptr<A> self;
};
A.cpp
#include "A.h"
#include <iostream>
A::A()
{
std::cout << "A 构造..." << std::endl;
self = std::shared_ptr<A>(this, [](A* a) { std::cout << "跳过 delete." << std::endl; });
pb = std::make_shared<B>(self);
pc = std::make_shared<C>(self);
}
A::~A()
{
std::cout << "A 析构..." << std::endl;
}
void A::Hello()
{
std::cout << "hello I am A Obj." << std::endl;
}
B.h
#pragma once
#include <memory>
class A;
class B
{
public:
B(std::shared_ptr<A> a);
~B();
std::shared_ptr<A> pa;
void Hello();
};
B.cpp
#include <iostream>
#include "B.h"
B::B(std::shared_ptr<A> a)
{
pa = a;
std::cout << "B 构造..." << std::endl;
}
B::~B()
{
std::cout << "B 析构..." << std::endl;
}
void B::Hello()
{
std::cout << "hello I am B Obj." << std::endl;
}
C.h
#pragma once
#include <memory>
class A;
class C
{
public:
C(std::shared_ptr<A> a);
~C();
std::shared_ptr<A> pa;
void Hello();
};
C.cpp
#include "C.h"
#include <iostream>
C::C(std::shared_ptr<A> a)
{
pa = a;
std::cout << "C 构造..." << std::endl;
}
C::~C()
{
std::cout << "C 析构..." << std::endl;
}
void C::Hello()
{
std::cout << "hello I am C Obj." << std::endl;
}
main.cpp
#include <memory>
#include "A.h"
int main()
{
auto a = std::make_shared<A>();
a->pb->Hello();
a->pc->Hello();
a->pb->pa->Hello();
a->pc->pa->Hello();
system("pause");
return 0;
}
输出:
A 构造...
B 构造...
C 构造...
hello I am B Obj.
hello I am C Obj.
hello I am A Obj.
hello I am A Obj.
请按任意键继续. . .
A 析构...
C 析构...
B 析构...
跳过 delete.
.exe (进程 15216)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .