So reparieren Sie Objektschneide (Speicherleck) [geschlossen]
Posted: 05 Apr 2025, 09:16
Ich habe einen Code (einfaches Beispiel) < /p>
Wie kann ich *f = *b; eine tiefe Kopie von *B bis *f ausführen und die Voraussetzung nicht auslaufen.
Code: Select all
#include
#include
#include
#include
class Foo {
public:
Foo() = default;
Foo(int j) {
i = new int[j];
}
virtual ~Foo() {
if (i) {
delete[] i;
}
}
private:
int* i;
};
class Bar: public Foo {
public:
Bar(int j) {
i = new char[j];
}
~Bar() {
delete[] i;
}
private:
char* i;
};
int main() {
int i = 5, j = 10;
Foo* f = new Foo(i);
Foo* b = new Bar(j);
*f = *b;
delete f;
delete b;
}
Code: Select all
class Foo {
public:
Foo() = default;
Foo(int j) : j_(j){
i = new int[j];
}
// base of idea from https://www.sandordargo.com/blog/2022/08/10/copy-and-swap-idiom-in-cpp
Foo& operator=(const Foo& other) {
if (this != &other) {
delete[] i;
i = new int[j_];
}
return *this;
}
virtual ~Foo() {
if (i) {
delete[] i;
}
}
private:
int j_;
int* i;
};