Storage class กำหนด scope (visibility) และ lifetime ของตัวแปรและ/หรือฟังก์ชันภายใน C++ Program Specifiers นี้มาก่อน type ที่พวกเขา modify มี storage classes ดังนี้ที่ใช้ใน C++ Program:
- auto
- register
- static
- extern
- mutable
ใน C, auto storage class specifier ให้ประกาศตัวแปรด้วย automatic storage อย่างชัดเจน auto เป็นค่าเริ่มต้นสำหรับตัวแปรในบล็อก ตัวแปร x ที่มี automatic storage ถูกลบเมื่อบล็อกที่ประกาศ x ออกจากการทำงาน
คุณใช้ auto storage class specifier ได้เฉพาะชื่อตัวแปรในบล็อกหรือพารามิเตอร์ฟังก์ชัน แต่ชื่อเหล่านี้มี automatic storage เป็นค่าเริ่มต้นอยู่แล้ว ดังนั้น auto มักซ้ำซ้อน
มันถูกนำมาใน C++ เริ่มต้นเพื่อความเข้ากันได้ทางไวยากรณ์อย่างเดียว แต่ภายหลังมีความหมายของตัวเอง คือ automatic type deduction
ใน C, register storage class specifier บอกคอมไพเลอร์ให้จัดเก็บ object ใน machine register ใช้กับตัวแปรที่ใช้บ่อย เช่น loop control variable เพื่อเพิ่มประสิทธิภาพ แตคอมไพเลอร์ไม่บังคับปฏิบัติ เนื่องจาก register จำกัด
Static storage class สั่งคอมไพเลอร์เก็บ local variable ตลอด lifetime ของโปรแกรม แทนที่จะสร้าง/ทำลายทุกครั้งที่เข้าออก scope ทำให้ local variables static รักษาค่าระหว่าง function calls ได้
Extern storage class specifier ให้ประกาศ objects ที่หลาย source files ใช้ร่วมกัน extern declaration ทำให้ variable ใช้ได้ในส่วนที่เหลือของ source file ไม่แทนที่ definition ใช้อธิบาย variable ที่ externally defined
Mutable storage class specifier ใช้เฉพาะ class data member ทำให้ modifiable ได้แม้ object เป็น const ไม่สามารถใช้กับ names ที่ประกาศ static หรือ const หรือ reference members
ตัวอย่าง
class A {
public:
A() : x(4), y(5) { };
mutable int x;
int y;
};
int main() {
const A var2;
var2.x = 345; // OK
// var2.y = 2345; // Error
}
คอมไพเลอร์ไม่อนุญาต var2.y = 2345 เพราะ var2 เป็น const แต่อนุญาต var2.x = 345 เพราะ A::x เป็น mutable