-1

Odd behavior in object creation using std::unique_ptr. Here are two example :

#include<iostream> 
#include<memory> 
using namespace std; 

class A 
{ 
public: 
    A() {
        throw "EOF";
    }
  void show() 
  { 
    cout<<"A::show()"<<endl; 
  } 
}; 

int main() 
{ 
    try {
      unique_ptr<A> p1 = make_unique<A>(); 
      p1 -> show(); 
    } catch(...) {
        cout << "Exception" << endl;
    }     
  return 0; 
} 

Output

Exception

This above output looks obvious. But, the below code's output is Odd.

// C++ program to illustrate the use of unique_ptr 
#include<iostream> 
#include<memory> 
using namespace std; 

class A 
{ 
public: 
    A() {
        throw "EOF";
    }
  void show() 
  { 
    cout<<"A::show()"<<endl; 
  } 
}; 

int main() 
{ 
    try {
      unique_ptr<A> p1; 
      p1 -> show(); 
    } catch(...) {
        cout << "Exception" << endl;
    }
  return 0; 
} 

Output

A::show()

These example are compiled with c++14 compiler. Is the above output expected behavior?

Mat
  • 202,337
  • 40
  • 393
  • 406
Soumya dutta
  • 79
  • 1
  • 7

2 Answers2

2

Your second example does not actually create an A object. It merely creates a unique_ptr to an A that is not initialized. Dereferencing such a pointer is Undefined Behaviour and the compiler is allowed to do whatever it wants, but you cannot rely on any specific behaviour. Example two is broken code.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
1

Is the above output expected behavior?

Yes, and no. There is no correct behaviour, because the behaviour of indirecting an empty smart pointer is undefined, just like indirecting a null pointer is. So, you shouldn't expect anything in particular, but nothing is unexpected either.

eerorika
  • 232,697
  • 12
  • 197
  • 326