Returning const reference to local variable from a function

后端 未结 4 1435
夕颜
夕颜 2020-11-29 18:11

I have some questions on returning a reference to a local variable from a function:

class A {
public:
    A(int xx)
    : x(xx)
    {
        printf(\"A::A()         


        
4条回答
  •  鱼传尺愫
    2020-11-29 18:59

    If you will compile this on VC6 you will get this warning

    ******Compiler Warning (level 1) C4172 returning address of local variable or temporary A function returns the address of a local variable or temporary object. Local variables and temporary objects are destroyed when a function returns, so the address returned is not valid.******

    While testing for this problem i found interesting thing (given code is working in VC6):

     class MyClass
    {
     public:
     MyClass()
     {
      objID=++cntr;
     }
    MyClass& myFunc()
    {
        MyClass obj;
        return obj;
    }
     int objID;
     static int cntr;
    };
    
    int MyClass::cntr;
    
    main()
    {
     MyClass tseadf;
     cout<<(tseadf.myFunc()).objID<

提交回复
热议问题