विषय पर बढ़ें

अंतिम अद्यतन:2026-10-12

C++ इनिशियलाइज़ेशन और असाइनमेंट

C++ iv

int* p = nullptr;
std::shared_ptr<int> s(p); // 计数器1
std::shared_ptr<int> s2(s); // 计数器2
assert(s.use_count() == 2); 

यह कोड कुछ सवाल खड़े करता है:

  • nullptr raw पॉइंटर से बने स्मार्ट पॉइंटर का काउंटर 0 क्यों नहीं होता?
  • क्या delete nullptr सुरक्षित है?

1.खाली shared_ptr की semantics

हम सीधे shared_ptr का सोर्स कोड देखते हैं, जिसे खाली (empty) कहा जाता है उससे तात्पर्य है:

  • डिफ़ॉल्ट कंस्ट्रक्टर से बना shared_ptr
  • nullptr_t से बना shared_ptr

केवल ये दो स्थितियाँ ही खाली हैं, जबकि raw पॉइंटर से बने shared_ptr की वह पॉइंटर की ownership होती है, भले वह खाली हो या न हो।

ये क्रमशः नीचे दिए तीन कंस्ट्रक्टरों से संबंधित हैं।

private:
    element_type*      __ptr_;
    __shared_weak_count* __cntrl_;

public:
    _LIBCPP_HIDE_FROM_ABI
    _LIBCPP_CONSTEXPR shared_ptr() _NOEXCEPT
        : __ptr_(nullptr),
          __cntrl_(nullptr)
    { }

    _LIBCPP_HIDE_FROM_ABI
    _LIBCPP_CONSTEXPR shared_ptr(nullptr_t) _NOEXCEPT
        : __ptr_(nullptr),
          __cntrl_(nullptr)
    { }
    shared_ptr(_Yp* __p, _Dp __d)
        : __ptr_(__p)
    {}

ऊपर raw पॉइंटर nullptr होने की स्थिति में, delete nullptr करने पर क्या होगा? दो बार delete करने पर क्या होगा?

2.delete nullptr

मान लीजिए नीचे का कोड है, चलाने के बाद crash होगा? या सही चलेगा?

#include <iostream>

int main() {
    int *p = nullptr;
    delete p;
    std::cout << "delete once" << std::endl;
    delete p;
    std::cout << "delete twice" << std::endl;

}

जवाब है: सामान्य आउटपुट।

सटीक कारण के लिए cppreference देखें:

If expression evaluates to a null pointer value, no destructors are called, and the deallocation function may or may not be called (it's unspecified), but the default deallocation functions are guaranteed to do nothing when passed a null pointer.

https://en.cppreference.com/w/cpp/language/delete

अगर एक्सप्रेशन का मूल्यांकन null पॉइंटर वैल्यू होता है, तो डिस्ट्रक्टर कॉल नहीं होते, और deallocation फ़ंक्शन कॉल हो भी सकता है और नहीं भी (यह unspecified है), लेकिन डिफ़ॉल्ट deallocation फ़ंक्शन null पॉइंटर पास होने पर कुछ न करने की गारंटी देते हैं।

पढ़ने की सलाह

यह लेख C++ में इनिशियलाइज़ेशन (initialization) और असाइनमेंट (assignment) के अंतर पर चर्चा करता है, देखें क्लास इनिशियलाइज़र लिस्ट।

संबंधित विषय

टिप्पणियाँ