निम्नलिखित कोड का टुकड़ा के लिए, यह तरीकों में अलग संदर्भ में गिना जाता है पता चलता है। क्या कोई समझा सकता है कि ये मान अलग क्यों हैं?क्यों स्थिरांक shared_ptr <const T> और और स्थिरांक shared_ptr <T> और दिखाने के अलग संदर्भ में गिना जाता है क्या ज़रूरत है?
class Foo {
};
void f1(const std::shared_ptr<Foo>& ptr) {
std::cout << "f1(): counts: " << ptr.use_count() << std::endl;
}
void f2(const std::shared_ptr<const Foo>& ptr) {
std::cout << "f2(): counts: " << ptr.use_count() << std::endl;
}
int main() {
std::shared_ptr<Foo> ptr(new Foo);
std::cout << "main(): counts: " << ptr.use_count() << std::endl;
f1(ptr);
f2(ptr);
std::cout << "main(): counts: " << ptr.use_count() << std::endl;
return 0;
}
इसी उत्पादन:
main(): counts: 1
f1(): counts: 1
f2(): counts: 2
main(): counts: 1
ऐसा नहीं है कि f2 कॉल shared_ptr से परिवर्तित shared_ptr करने के भाग के रूप एक अंतर्निहित अस्थायी वस्तु का निर्माण करने के लिए किया था की संभावना है, और वह यह है कि जहां दूसरे refcount जब f2 निष्पादित हो रहा है से आ रही है। –
धन्यवाद! सही बात। –
बिल्कुल संबंधित नहीं हैं, बस FYI करें: आप [का उपयोग '' new' के बजाय make_shared'] चाहिए (https://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/) – Tas