So reparieren Sie Objektschneide (Speicherleck) [geschlossen]C++

Programme in C++. Entwicklerforum
Anonymous
 So reparieren Sie Objektschneide (Speicherleck) [geschlossen]

Post by Anonymous »

Ich habe einen Code (einfaches Beispiel) < /p>

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;
}
Wie kann ich *f = *b; eine tiefe Kopie von *B bis *f ausführen und die Voraussetzung nicht auslaufen.

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;
};

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post