2016-09-17 7 views
7

यदि मैं एक स्थिर वस्तु में this लेता हूं और इसे सिंगलटन ऑब्जेक्ट में वेक्टर में संग्रहीत करता हूं, तो क्या मैं प्रोग्राम के पूरे जीवनकाल के दौरान ऑब्जेक्ट पर पॉइंटर पॉइंट मान सकता हूं?एक स्थैतिक वस्तु का यह सूचक

+1

यदि आप इस तरह सिंगलटन करते हैं, तो http://stackoverflow.com/questions/6993400/managing-a-singleton-destructor/6993501#6993501, तब तक जब तक आप प्रबंधन सिंगलटन से इंस्टेंस तक पहुंचें, ऑर्डर करें निर्माण और विनाश प्रभावी ढंग से गारंटीकृत है। – Nim

उत्तर

2

सामान्य रूप से, आप यह नहीं मान सकते हैं, क्योंकि अलग-अलग अनुवाद इकाइयों में स्थैतिक वस्तु निर्माण का क्रम निर्दिष्ट नहीं है। इस मामले में यह काम करेंगे, क्योंकि वहाँ केवल एक अनुवाद इकाई:

#include <iostream> 
#include <vector> 
class A 
{ 
    A() = default; 
    A(int x) : test(x) {} 
    A * const get_this(void) {return this;} 
    static A staticA; 
public: 
    static A * const get_static_this(void) {return staticA.get_this();} 
    int test; 
}; 

A A::staticA(100); 

class Singleton 
{ 
    Singleton(A * const ptr) {ptrs_.push_back(ptr);} 
    std::vector<A*> ptrs_; 
public: 
    static Singleton& getSingleton() {static Singleton singleton(A::get_static_this()); return singleton;} 
    void print_vec() {for(auto x : ptrs_) std::cout << x->test << std::endl;} 
}; 

int main() 
{ 
    std::cout << "Singleton contains: "; 
    Singleton::getSingleton().print_vec(); 

    return 0; 
} 

आउटपुट:

Singleton contains: 100 

लेकिन क्या अलग अनुवाद इकाई में परिभाषित में A::staticA तो क्या होगा? क्या इसे static Singleton से पहले बनाया जाएगा? आप सुनिश्चित नहीं हो सकते हैं।

संबंधित मुद्दे