vendredi 3 janvier 2020

Scope of variable local to static method in C++

I was trying to create an instance of an object with private constructor. Is this method correct?

#include <iostream> 
using namespace std; 
class A{
    int y;
    A(int y=2):y(y){};
    public:
    A(const A &obj){
        cout<<"copy Cotr is called"<<endl;
        this->y=obj.y;
    }
    int* addr(){
        int *a=&y;
        return a;
    }
    static A create(int y1=2){
        class A a(y1);
        cout<<&a<<endl;
        return a;
    }
    void print(){
        cout<<y<<endl;
    }
};
int main(){
    A o1=A::create(1);
    A o2=A::create(3);
    cout<<&o1<<" "<<&o2<<endl;
    return 0;
}

The output is:

0x7ffd20d2f280
0x7ffd20d2f284
0x7ffd20d2f280 0x7ffd20d2f284

In the above code, I fail to understand few points:

  1. create() returns a value, so during assignment which take place in A o1=A::create(1);, copy constructor should be called but it isn't. why?
  2. Is this some undefined behavior as the address of the object created in create() and in main() are same and the object in create() is local and goes out of scope after the function ends.

Aucun commentaire:

Enregistrer un commentaire