stl源码学习(版本2.91)--listnode
1,默认构造函数的做用和被调用的时机c++
struct no{ no(int i){} //no(){ // std::cout << "s" << std::endl; //} long data; }; struct A{ no n; }; int main(){ A a; }
这段代码报错,提示没法构造A类的a对象,编译器会给A类提供默认构造函数,可是A类的默认构造函数去构造它成员no类的n时,发现no类没有构造函数(理由:由于本身定义了no(int)构造函数,因此编译器就不提供no类的默认构造函数了),因此就没法构造n对象,也就没法构造a对象了。微信
1.cpp: In function ‘int main()’: 1.cpp:22:5: error: use of deleted function ‘A::A()’ A a; ^ 1.cpp:12:8: note: ‘A::A()’ is implicitly deleted because the default definition would be ill-formed:
2,allocator和定位new的用法函数
stl_list.h源码节选学习
template <class T> struct __list_node { typedef void* void_pointer; void_pointer next; void_pointer prev; T data; }; template <class T, class Alloc = alloc> class list { protected: typedef __list_node<T> list_node; typedef simple_alloc<list_node, Alloc> list_node_allocator; public: typedef list_node* link_type; protected: link_type node;//list惟一的成员,是end()函数的返回值 public: list() { empty_initialize(); } protected: void empty_initialize() { node = get_node(); node->next = node; node->prev = node; } protected: link_type get_node() { return list_node_allocator::allocate(); } link_type create_node(const T& x) { link_type p = get_node(); __STL_TRY { construct(&p->data, x); } __STL_UNWIND(put_node(p)); return p; } S iterator insert(iterator position, const T& x) { link_type tmp = create_node(x); tmp->next = position.node; tmp->prev = position.node->prev; (link_type(position.node->prev))->next = tmp; position.node->prev = tmp; return tmp; }
stl_alloc.hcode
template<class T, class Alloc> class simple_alloc { public: static T *allocate(size_t n) { return 0 == n? 0 : (T*) Alloc::allocate(n * sizeof (T)); } static T *allocate(void) { return (T*) Alloc::allocate(sizeof (T)); }
stl_construct.horm
template <class T1, class T2> inline void construct(T1* p, const T2& value) { new (p) T1(value); }
从以上的stl list源码能够看出:对象