का उपयोग करते समय std :: स्ट्रिंग के साथ मेमोरी लीक मैं अपने वर्तमान प्रोजेक्ट में std::list<std::string>
के साथ काम कर रहा हूं। लेकिन इसके साथ कहीं जुड़े एक स्मृति रिसाव है। इसलिए मैंने समस्याग्रस्त कोड को अलग से परीक्षण किया है:std :: string <std::string>
#include <iostream>
#include <string>
#include <list>
class Line {
public:
Line();
~Line();
std::string* mString;
};
Line::Line() {
mString = new std::string("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
}
Line::~Line() {
//mString->clear(); // should not be neccessary
delete mString;
}
int main(int argc, char** argv)
{
// no memory leak
while (1==1) {
std::string *test = new std::string("XXXXXXXXXXXXXXXXXXXXXXXX");
delete test;
}
// LEAK!
// This causes a memory overflow, because the string thats added
// to the list is not deleted when the list is deleted.
while (1==1) {
std::list<std::string> *sl = new std::list<std::string>;
std::string *s = new std::string("XXXXXXXXXXXXXXXXXXXXXXX");
sl->push_back(*s);
//sl->pop_back(); //doesn't delete the string?- just the pointer
delete sl;
}
// LEAK!
// Here the string IS deleted, but the memory does still fill up
// but slower
while (1==1) {
std::list<Line> *sl = new std::list<Line>;
Line *s = new Line();
sl->push_back(*s);
//sl->pop_back(); //does delete the Line-Element
sl->clear();
delete sl;
}
return 0;
// this does not cause any noticable memory leak
while (1==1) {
std::list<int> *sl = new std::list<int>;
int i = 0xFFFF;
sl->push_back(i);
sl->clear();
delete sl;
}
return 0;
// This does not cause any overflow or leak
while (1==1) {
int *i;
i= new int [9999];
delete[] i;
}
}
मेरी स्ट्रिंग सूची मेमोरी रिसाव क्यों करती है? सूची को हटाना नहीं चाहिए क्योंकि प्रत्येक निहित स्ट्रिंग पर विनाशकों को बुलाया जाना चाहिए?
'नया' का उपयोग करना बंद करें। मैं आपके द्वारा कहीं भी नए इस्तेमाल किए गए किसी भी कारण को नहीं देख सकता। आप सी ++ में मूल्य से वस्तुओं को बना सकते हैं और यह भाषा का उपयोग करने के लिए एक बड़ा लाभ है। आपको ढेर पर सबकुछ आवंटित करने की आवश्यकता नहीं है। जावा प्रोग्रामर की तरह सोचना बंद करो। – Omnifarious