C++ 静态对象

来源:互联网 发布:windows vista和win7 编辑:程序博客网 时间:2024/06/05 16:11

Static in C++

Two basic meanings

Static Storage

--allocated once at a fixed address

Visibility of a name

--internal linkage

Don’t use static except inside functions and classes.

Uses of “static” in C++

Static free functions—-deprecated弃用

Static globle variables—-deprecated弃用

Static local variables—-Persistent storage持久存储

Static member variables—-Shared by all instances所有对象共享

Static member functions—-Shared by all instances, can only access static member variables所有对象共享,只能访问静态变量或静态函数

Static inside functions

Value is remembered for entire program

Initialization occurs only once

Static applied to objects…

Constructors are called before main() is entered

--Constructor called at-most once--main() is no longer the first function called--The constructor arguments must be satisfied

Destructors called when

--main() exited--exited is called

–Compiler assures LIFO order of destructors

Can we apply static to members?

Static means

--Hidden(now usually use public,protected,private)--Persistant

Hidden: A static member is a member

--Obeys usual access rules

Persistant: Independent of instances
假设有一个类:

class A{ A(int,int); ~A(); ...}void f(){ static A a(6,6); ...}

对象 a 的初始化发生在第一次进f() 函数的时候,空间在全局变量区,在编译(链接)的时候分配空间。
(而全局变量的构造发生在程序运行的时候,在main()之前)