c++ - Destructor called twice causes crash -


i implemented constructor takes string argument, causes destructor called twice , program crashes (the program contains raw pointer). know has copy constructor somehow gets called when type of constructors used. below simple code illustrates problem.

i appreciate comments on how fix program avoid crash. need use kind of constructors. understand why copy constructor gets called. didn't explicit assignment.

#include <iostream> #include <fstream> #include <string> using namespace std;  class debugclass { public:     debugclass(void) {         data = null;     }      debugclass(std::string str) {         data = new double[2];         data[0] = 1.0;         data[1] = 2.0;     }      debugclass(debugclass const& other) {         cout << "copy construction\n";      }      ~debugclass(void) {         if (data)         {             delete [] data;             data = null;         }     }      double* data; };   int main() {     debugclass obj = debugclass("folder");     return 0; } 

your copy constructor leaves data uninitialized:

debugclass::debugclass(debugclass const& other)  {      cout << "copy construction\n";  } 

so use of data point on give undefined behaviour.

if set data nullptr there, should not double deletion. though want form of copying other.

this line:

debugclass obj = debugclass("folder"); 

results in copy constructor being called part of constructing obj.

if instead did:

debugclass obj("folder"); 

then obj constructed normal constructor.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -