前言
現(xiàn)在開發(fā)的項(xiàng)目中用到了大部分 C++ 代碼,由于 Swift 和 C++ 混編不是很方便, 依然選擇用 OC 混編, 只需要將 .m文件 修改為 .mm文件即可。
OC 里的對象大部分都會加入自動(dòng)釋放池中,所以這些都不用手動(dòng)釋放,但是 C++ 對象不會被加入自動(dòng)釋放池,必須要手動(dòng)釋放,否則會造成內(nèi)存泄漏。
.mm文件中可以隨意的 new CppObject(), 但是要記得 delete 。當(dāng)cpp指針被當(dāng)前對象引用時(shí),當(dāng)前對象的dealloc 方法里要記得釋放該資源。
借助這個(gè)機(jī)會,重溫一下 C++的內(nèi)存管理 以及 智能指針的使用。
普通指針
單獨(dú)的對象
ComparePooling* mPool = new ComparePooling(); // 釋放mPool delete mPool;這是最簡單的。。。
釋放 C++ 數(shù)組
TestA * aList = new TestA[10]; // 釋放數(shù)組對象 delete []aList;
釋放vector (stack)對象
for(vector<MidiPart *>::iterator it = this->mParts.begin(); it != this->mParts.end(); it ++){ if (NULL != *it) { delete *it; *it = NULL; } } this->mParts.clear();
現(xiàn)在考慮下面情況
void func() { int *p = new int(5); do something... throw "exception occured"; delete p; } int main(){ try { func(); } catch (const char* str) { std::cout<<str <<std:endl; } }
func函數(shù) 中 可能會觸發(fā)異常,是函數(shù)提前退出,這樣有可能資源不會得到釋放。有效使用 智能指針 可以解決這一問題。
智能指針
智能指針的原理就是將你 new 出來的一個(gè)指針ptr傳給他,它返回一個(gè)棧上的對象 A 給你。這個(gè)對象保存著你傳入的 ptr。 當(dāng) A 離開作用域(無論是命名空間還是函數(shù),還是拋出異常提前退出), A 的析構(gòu)函數(shù)都會被調(diào)用,析構(gòu)函數(shù)內(nèi)部會 釋放ptr指針。所以使用智能指針會為資源管理提供方便。
auto_ptr
class ObjectA {
public:
~ObjectA(){
std::cout<<"TestA did release"<<std::endl;
}
ObjectA(int age): mAge(age) {}
int mAge;
};
int main(int argc, const char * argv[]) {
// insert code here...
std::auto_ptr<ObjectA> ptr_a( new ObjectA(20) );
std::cout<< ptr_a->mAge << std::endl;
return 0;
}
outPut如下
20
TestA did release
若要手動(dòng)釋放可以調(diào)用 reset() 函數(shù)
int main(int argc, const char * argv[]) {
std::auto_ptr<ObjectA> ptr_a( new ObjectA(20) );
ptr_a.reset();
std::cout<< ptr_a->mAge << std::endl; // Crash !!!
return 0;
}
對象已被釋放,再次訪問就會變成野指針,程序會崩潰。
當(dāng)reset() 方法傳入?yún)?shù)時(shí)會替換掉內(nèi)部保持的指針
int main(int argc, const char * argv[]) {
std::auto_ptr<ObjectA> ptr_a( new ObjectA(20) );
ptr_a.reset(new ObjectA(40));
std::cout<< ptr_a->mAge << std::endl; // outPut : 40
return 0;
}
另外 auto_ptr 不能指向一個(gè)數(shù)組對象,會直接crash。因?yàn)樗鼉?nèi)部 使用的 delete ptr , 而不是 delete[] ptr。
shared_ptr
shared_ptr 有一種共享所有權(quán)的概念,n 個(gè)指針可以同時(shí)指向一個(gè)對象,這個(gè)對象的引用計(jì)數(shù)就為 n,知道最后一個(gè)對象離開作用域時(shí)才會釋放該對象 。所以當(dāng)我第一次接觸 iOS 的 ARC 機(jī)制中的強(qiáng)引用(strong)時(shí),感覺如此熟悉。
int main(){
{
std::cout << "constructor with no managed object\n";
std::shared_ptr<ObjectA> sh1;
}
{
std::cout << "constructor with object\n";
std::shared_ptr<ObjectA> sh2(new ObjectA);
std::shared_ptr<ObjectA> sh3(sh2);
std::cout << sh2.use_count() << '\n';
std::cout << sh3.use_count() << '\n';
}
{
std::cout << "constructor with object and deleter\n";
std::shared_ptr<ObjectA> sh5(new ObjectA, [](auto p) {
std::cout << "Call delete from lambda...\n";
delete p;
});
}
}
outPut 如下
constructor with no managed object
constructor with object
2
2
ObjectA did release
constructor with object and deleter
Call delete from lambda...
ObjectA did release
shared_ptr 的構(gòu)造函數(shù) 可以用一個(gè)deleter (lambada 表達(dá)式) 作為參數(shù)
template< class Y, class Deleter > shared_ptr( Y* ptr, Deleter d );
std::shared_ptr<ObjectA> sh5(new ObjectA, [](auto p) {
std::cout << "Call delete from lambda...\n";
delete p;
});
那么我們想傳入一個(gè)數(shù)組對象時(shí)就可以如下操作
std::shared_ptr<ObjectA> sh5(new ObjectA, [](auto p) {
delete[] p;
});
循環(huán)引用
將shared_ptr 隨意強(qiáng)引用給其他對象,可能會造成循環(huán)引用
#include <iostream>
class ObjectB;
class ObjectA {
public:
~ObjectA(){
std::cout<<"ObjectA did release"<<std::endl;
}
ObjectA() {}
std::shared_ptr<ObjectB> mPtrB;
};
class ObjectB {
public:
~ObjectB(){
std::cout<<"ObjectB did release"<<std::endl;
}
ObjectB() {}
std::shared_ptr<ObjectA> mPtrA;
};
int main(){
{
std::shared_ptr<ObjectA> ptr_a (new ObjectA);
std::shared_ptr<ObjectB> ptr_b (new ObjectB);
ptr_a->mPtrB = ptr_b;
ptr_b->mPtrA = ptr_a;
}
}
上面的 ObjectA 和 ObjectB 都不會被釋放.
ObjectA -> ptr_b -> ObjectB -> ptr_a -> ObjectA
造成了循環(huán)引用,所以為了解決這一問題, C++ 提供了 弱指針 如下。
weak_ptr
weak_ptr 是對源對象的弱引用,weak_ptr 指向該對象是,該對象的 引用計(jì)數(shù)不會加一。
weak_ptr 的創(chuàng)建一般用一個(gè)shared_ptr 對象 作為參數(shù)。
void main( ){
shared_ptr<ObjectA> sptr( new ObjectA );
weak_ptr<ObjectA> wptr( sptr );
weak_ptr<ObjectA> wptr1 = wptr;
}
當(dāng) shared_ptr 離開了自己的定義域后,shared_ptr 被釋放。weak_ptr 指向的對象也就釋放了,weak_ptr 對象的引用計(jì)數(shù)為 0。
void main(){
std::weak_ptr<ObjectA> w_ptr;
{
std::shared_ptr<ObjectA> ptr(new ObjectA);
w_ptr = ptr;
std::cout << "w_ptr.use_count() inside scope: " << w_ptr.use_count() << '\n';
}
std::cout << "w_ptr.use_count() out of scope: " << w_ptr.use_count() << '\n';
std::cout << "w_ptr.expired() out of scope: " << std::boolalpha << w_ptr.expired() << '\n';
}
outPut 如下
w_ptr.use_count() inside scope: 1
ObjectA did release
w_ptr.use_count() out of scope: 0
w_ptr.expired() out of scope: true
unique_ptr
unique_ptr 和 auto_ptr 類似。在任何時(shí)間點(diǎn),對象只能被一個(gè) unique_ptr 所持有。unique_ptr 不支持普通的拷貝和賦值操作。
void main()
{
// 創(chuàng)建一個(gè)unique_ptr實(shí)例
unique_ptr<int> pInt(new int(5));
unique_ptr<int> pInt2(pInt); // 報(bào)錯(cuò)
unique_ptr<int> pInt3 = pInt; // 報(bào)錯(cuò)
}
unique_ptr雖然沒有支持普通的拷貝和賦值操作,但卻提供了一種移動(dòng)機(jī)制來將指針的所有權(quán)從一個(gè)unique_ptr轉(zhuǎn)移給另一個(gè)unique_ptr。如果需要轉(zhuǎn)移所有權(quán),可以使用std::move()函數(shù)。
void main()
{
unique_ptr<int> pInt(new int(5));
unique_ptr<int> pInt2 = std::move(pInt); // 轉(zhuǎn)移所有權(quán)
//cout << *pInt << endl; // 出錯(cuò),pInt為空
cout << *pInt2 << endl;
unique_ptr<int> pInt3(std::move(pInt2));
}
下面看個(gè)??子
#include <iostream>
#include <vector>
#include <memory>
#include <cstdio>
#include <cassert>
#include <functional>
struct B {
virtual void bar() { std::cout << "B::bar\n"; }
virtual ~B() = default;
};
struct D : B
{
D() { std::cout << "D::D\n"; }
~D() { std::cout << "D::~D\n"; }
void bar() override { std::cout << "D::bar\n"; }
};
// a function consuming a unique_ptr can take it by value or by rvalue reference
std::unique_ptr<D> pass_through(std::unique_ptr<D> p)
{
p->bar();
return p;
}
int main()
{
std::cout << "unique ownership semantics demo\n";
{
auto p = std::make_unique<D>(); // p is a unique_ptr that owns a D
auto q = pass_through(std::move(p));
assert(!p); // now p owns nothing and holds a null pointer
q->bar(); // and q owns the D object
} // ~D called here
std::cout << "Runtime polymorphism demo\n";
{
std::unique_ptr<B> p = std::make_unique<D>(); // p is a unique_ptr that owns a D
// as a pointer to base
p->bar(); // virtual dispatch
std::vector<std::unique_ptr<B>> v; // unique_ptr can be stored in a container
v.push_back(std::make_unique<D>());
v.push_back(std::move(p));
v.emplace_back(new D);
for(auto& p: v) p->bar(); // virtual dispatch
} // ~D called 3 times
std::cout << "Custom lambda-expression deleter demo\n";
{
std::unique_ptr<D, std::function<void(D*)>> p(new D, [](D* ptr)
{
std::cout << "destroying from a custom deleter...\n";
delete ptr;
}); // p owns D
p->bar();
} // the lambda above is called and D is destroyed
std::cout << "Array form of unique_ptr demo\n";
{
std::unique_ptr<D[]> p{new D[3]};
} // calls ~D 3 times
}
Output:
unique ownership semantics demo
D::D
D::bar
D::bar
D::~D
Runtime polymorphism demo
D::D
D::bar
D::D
D::D
D::bar
D::bar
D::bar
D::~D
D::~D
D::~D
Custom lambda-expression deleter demo
D::D
D::bar
destroying from a custom deleter...
D::~D
Array form of unique_ptr demo
D::D
D::D
D::D
D::~D
D::~D
D::~D
總結(jié)
實(shí)際coding中,還是shared_ptr 使用的多。代碼中避免不了將對象賦值給其他對象。