About destructors in c++ -
the question how correctly delete name in a destructor?
class a{ private: char *name; public: a(char *n) : name(n) {} ~a(){ //??? } } int main(){ *a = new a("name"); delete a; return 0; }
given not change constructor, correct way not delete anything. ownership of string belongs client, since not creating copy.
however, right way of rewriting let constructor allocate copy of string new[]
, let destructor deallocate delete[]
.
and really right way let std::string
whole thing you, , not write explicit destructor @ all:
#include <string> class a{ private: std::string name; public: a(std::string n) : name(std::move(n)) {} };
this, way, allows not worry rule of three, means won't have bother writing copy constructor, move constructor, copy assignment operator, move assignment operator, destructor , whatnot.
Comments
Post a Comment