c++ - constructor and copy constructor -


#include <iostream>  using namespace std;  class t{ private: int * arr;  public:     t() { arr=new int[1]; arr[0]=1;}     t(int x) {arr=new int[1]; arr[0]=x;}     t(const t &);     ~t() {cout<<arr[0]<<"   de"<<endl; delete [] arr;}     t & operator=(const t & t1){arr[0]=t1.arr[0];return *this;}     void print(){cout<<arr[0]<<endl;}  }; t::t(const t & t1) {arr=new int[1];arr[0]=t1.arr[0];}  int main(){     t b=5;    cout<<"hello"<<endl;    b.print();    b=3;     b.print();    return 0; } 

why result

hello 5 3   de  3 3   de ? 

why "t b=5;" not call destructor? how "t b=5" works? create temp object (of class t) using constructor "t(int x)" first, use copy constructor "t(const t &)" create b? if case why not call desctructor temp object?

why "t b=5;" not call destructor?

when this:

t b=5; 

you copy initialization. semantically, implicit converting constructor t(int) called, , copy constructor t(const t&) called instantiate b. however, compiler allowed elide copy, happening in case. object constructed in place, without need copy construction. why not see destructor call. class still needs copy constructor code compile: copy elision optional, , whether code compiles should not depend on whether compiler performing elision or not.

if had said

t b(5); 

then there direct initialization, no copy elision, , 1 constructor call. class not require copy constructor in code compile.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -