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

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -