Was ist "minimaler Rahmen" (notwendige Methoden) von komplexen Objekt (mit explizit mallocated internen Daten), die ich in STL-Container, z. <vector>
?Speichern von Objekten in STL-Vektor - minimale Menge von Methoden
Für meine Annahmen (zB von komplexen Objekt Doit):
#include <vector>
#include <cstring>
using namespace std;
class Doit {
private:
char *a;
public:
Doit(){a=(char*)malloc(10);}
~Doit(){free(a);}
};
int main(){
vector<Doit> v(10);
}
gibt
*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0804b008 ***
Aborted
und in valgrind:
malloc/free: 2 allocs, 12 frees, 50 bytes allocated.
UPDATE:
Minimal Methoden für solche obj ect sind: (basierend auf sbi Antwort)
class DoIt{
private:
char *a;
public:
DoIt() { a=new char[10]; }
~DoIt() { delete[] a; }
DoIt(const DoIt& rhs) { a=new char[10]; std::copy(rhs.a,rhs.a+10,a); }
DoIt& operator=(const DoIt& rhs) { DoIt tmp(rhs); swap(tmp); return *this;}
void swap(DoIt& rhs) { std::swap(a,rhs.a); }
};
Danke, sbi, https://stackoverflow.com/users/140719/sbi
Benötigen Sie einen Vergleich? –
Sie sollten wirklich Vektoren von anstelle von Ihren eigenen mallocs verwenden. Das ist schließlich C++. –
Joe
nein. aber ich brauche wirklich einen Zeiger in einem Objekt, das malloced ist. – osgx