মেমরি মডেল
C++-এ অবজেক্ট দুটি জায়গায় সংরক্ষিত হতে পারে:
- Stack: ব্লক/ফাংশন-এর ভেতরে ঘোষিত সব ভেরিয়েবল/অবজেক্ট। স্কোপ শেষ হলে অটোমেটিক্যালি ডিস্ট্রয় হয়।
- Heap:
newঅপারেটর দিয়ে ডাইনামিক্যালি অ্যালোকেটেড অবজেক্ট। ম্যানুয়ালিdeleteকরতে হয়।
উদাহরণ: Stack vs Heap অবজেক্ট লাইফসাইকেল
#include <iostream>
using namespace std;
class Box {
int width, length;
public:
Box(int l = 0, int w = 0) : length(l), width(w) {}
~Box() { cout << "Box is destroying" << endl; }
int get_len() { return length; }
int get_width() { return width; }
};
int main() {
// Stack object
{
Box b(2, 3); // স্ট্যাক-এ
cout << "Box dimension: " << endl;
cout << "Length: " << b.get_len() << endl;
cout << "Width: " << b.get_width() << endl;
} // ব্লক শেষ, ডিস্ট্রাক্টর অটো কল
cout << "\tExiting block, destructor automatically called for stack object." << endl;
// Heap object
Box* box_ptr;
{
Box* box_ptr1 = new Box(5, 6); // হিপ-এ
box_ptr = box_ptr1;
cout << "Box 2 dimension: " << endl;
cout << "Length: " << box_ptr1->get_len() << endl;
cout << "Width: " << box_ptr1->get_width() << endl;
delete box_ptr1; // ম্যানুয়ালি ডিলিট
}
// box_ptr এখন ড্যাঙ্গলিং পয়েন্টার
cout << "Length of box2: " << box_ptr->get_len() << endl; // অনির্দিষ্ট আচরণ
cout << "Width of box2: " << box_ptr->get_width() << endl;
}
আউটপুট
Box dimension is:
Length : 2
Width : 3
Box is destroying
Exiting block, destructor automatically called for stack object.
---------------------------------------------------
Box 2 dimension is:
length : 5
width : 6
Box is destroying
length of box2 : 0
width of box2 : 0
নোট
delete করার পর পয়েন্টার ব্যবহার করা অনির্দিষ্ট আচরণ (undefined behavior)। স্মার্ট পয়েন্টার (unique_ptr, shared_ptr) ব্যবহার করা ভালো অভ্যাস।