在面试或者被面试过程中收集的面试题目,不仅仅与C++相关,还有数据结构和算法,系统等等。
C++
_如何让两个shared_ptr指向同一个实例_
enable_shared_from_memory
今天听面试人说的,以前真没考虑过
只在堆或者栈上创建对象
只在堆上 : operator new()=delete
只在栈上 : private ~base();
static成员变量不能在类内部初始化吗
Case 1
1 2 3 4
| static const int m_iCount = 100; static const float m_fCount = 1.0f; const int m_iCount = 100; const float m_fCount = 1.f;
|
Case 2
1 2 3 4 5 6 7 8 9 10 11 12 13
| class base{ public: base(){cout<<"base construct"<<endl;} private: static base m_bObject; }
int main(){ return 0; }
output : 空
|
对m_bObject没有进行类外初始化,但好像也没有调用base的构造函数。
Case 3
1 2 3 4 5 6 7 8 9 10 11 12 13
| class base{ public: base(){cout<<"base construct"<<endl;} private: static base m_bObject; } base m_bObject; int main(){ return 0; }
output : base construct
|
对m_bObject没有进行类外初始化,但好像也没有调用base的构造函数,难道static成员可以不同初始化,除非要使用?
Case 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class base{ public: base(i){cout<<"base construct"<<endl;} static base& getInstance(){ m_bObject = base(100) } private: static base m_bObject; } base m_bObject; int main(){ return 0; }
output : error: no matching function for call to ‘base::base()’
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class base{ public: base(){cout<<"base construct no param";} static void print(){ std::cout << "test" << std::endl; } static void Init(){ static base temp; m_bObject = temp; return; } public: static base m_bObject; };
int main() { base::m_bObject.print(); base::print(); b.print(); return 0; }
|
这里有两个问题
从上面可以总结得出
- static变量在未使用之前可以不用初始化
- static成员变量不会默认初始化(如果不在类外初始化的话)
- static成员类外初始化