c++ - Constructor/Destructor function not being called while calling by value or reference. Any way around it? -
c++ - Constructor/Destructor function not being called while calling by value or reference. Any way around it? -
i'm having problem because of feature of c++. after working dynamic memory allocation, clear heap(free store) because of obvious reasons. destructor function. , sometime, allocate memory using constructor. after calling object function(call value), destructor works. know it's feature in many cases. but, annoying while working lot of stand-alone functions. way around it,guys? or, should utilize fellow member function allocate , clear memory?
an example:
#include <iostream> using namespace std; class test{ int *a; public: test(int x) {a=new int; *a=x;} int geta(){return *a;} ~test(){delete a;} }; int apow2(test t) { homecoming ((t.geta())*(t.geta())); } int main() { test tst(10); cout<<"\na^2="<<apow2(tst); //at point, memory reference 'a' doesn't exist cout<<"\n"<<tst.geta(); homecoming 0; }
you're having problem because did not implement copy constructor , copy assignment operator class test
: you did not abide rule of three.
but, news! don't need to. can avoid all of kerfuffle storing int
instead of int*
:
class test { int a; public: test(int x) : a{x} {} };
that's it! no dynamic allocation, no memory management, nothing. test
, , int
assured survive exactly test
's lifetime. perfect.
if need dynamic allocation reasons not stated in question (whoops), should utilize smart pointer manage lifetime you:
class test { std::unique_ptr<int> a; public: test(int x) : a{new int(x)} {} int geta() { homecoming *a; } };
that's it! no memory management, nothing. test
, , int*
pointee assured survive exactly test
's lifetime. perfect.
c++ oop constructor destructor
Comments
Post a Comment