কম্পিউটার টিউটোরিয়াল

C++-এ ব্লকের ভেতরে তৈরি অবজেক্ট কোথায় সংরক্ষিত হয়? (Stack vs Heap)


মেমরি মডেল

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) ব্যবহার করা ভালো অভ্যাস।

  1. স্ট্রাকচারে ছাত্রের তথ্য সংরক্ষণ করার C++ প্রোগ্রাম

  2. মাল্টি-ডাইমেনশনাল অ্যারে ব্যবহার করে দুটি ম্যাট্রিক্স যোগ করার C++ প্রোগ্রাম

  3. C++ স্ট্যান্ডার্ড আউটপুট স্ট্রিম (cout) কী?

  4. C++-এ Python অবজেক্ট কীভাবে ব্যবহার করবেন?