The problem is with class A’s constructor, when A has a constructor like that, it is no longer the special case anymore, but belongs to the Exception 3 now.
thank you for your reply. But I am confused as if why Special case Works but Exception 4 does not. Why would c++ committee provide this confusing exception? We are just making one object on the heap while another one on the stack. can you share your views on the same?
The special case works because of “copy elision”. The temporary object is constructed directly “in place”, so there is no “copy” of the reference, thus the lifetime of the temporary object could be extended.
A special case does not work in the following example, any idea why?
class A{
public:
const int &val;
public:
A(const int ¶m): val(param)
{
cout<<“\nInside the construtor , val = “<<val;
}
};
int main() {
A obj(4);
cout<<“\nValue of mem val = “<<obj.val;
return 0;
}
The problem is with class A’s constructor, when A has a constructor like that, it is no longer the special case anymore, but belongs to the Exception 3 now.
thank you for your reply. But I am confused as if why Special case Works but Exception 4 does not. Why would c++ committee provide this confusing exception? We are just making one object on the heap while another one on the stack. can you share your views on the same?
The special case works because of “copy elision”. The temporary object is constructed directly “in place”, so there is no “copy” of the reference, thus the lifetime of the temporary object could be extended.