乙個類用的是智慧型指標指向的vector,乙個類的用的是裸的vector. 在拷貝物件的時候出現不一樣.
智慧型指標版:
編譯:#include #include #include #include #include using std::initializer_list;
using std::string;
using std::vector;
using std::make_shared;
class strblob
vector::size_type size() const
private:
std::shared_ptr> data;
};
strblob::strblob(): data(make_shared>()) {}
strblob::strblob(initializer_listil): data(make_shared>(il)) {}
int main()
; strblob c = b;
c.push_back("world");
std::cout << b.size() << std::endl;
return 0;
}
g++ -std=c++11 -wall -o strblob_p405 strblob_p405.cpp
輸出為: 2
由此可見,兩個物件共用的是同乙個底層的vector.
普通版:
輸出為1, 兩個物件b 和 c 分別使用各自的vector, 互不干擾.#include #include #include #include #include using std::initializer_list;
using std::string;
using std::vector;
using std::make_shared;
class strblob
vector::size_type size() const
private:
std::vectordata;
};strblob::strblob(): data(vector()) {}
strblob::strblob(initializer_listil): data(vector(il)) {}
int main()
; strblob c = b;
c.push_back("world");
std::cout << b.size() << std::endl;
return 0;
}
參考: <
智慧型指標的乙個bug
先show乙個例項 class father father virtual void fun class mother mother virtual void test int a class son publicfather public mother son void fun int tmain...
乙個簡單的C 智慧型指標的實現
c 在堆上分配的記憶體需要分配者自己釋放,但是有時分配者由於某種情況忘記釋放,此時會造成記憶體洩漏,因此實現了乙個簡單的智慧型指標。引用計數類,負責管理動態分配的記憶體的使用者數量 class reference reference 自增 int add 自減 int release private...
關於智慧型指標的乙個有趣的筆記
這幾天比較好奇就是c 的智慧型指標在離開作用域之後是否會被銷毀,疑惑點來自自己寫的一段小 int count 0 vector observers typedef std vector iterator iterator while 1 shared ptrp new foo weak ptrw p...