C++ 11 Quizz
Predict the output of the below set of programs
[1]
#include <iostream>
#include<memory>
void foo(std::shared_ptr<int> i)
{
(*i)++;
}
int main ()
{
auto ptr = std::make_shared<int>(23);
foo(ptr);
cout<<*ptr<<endl;
return 0;
}
[2] Can you change the baove program now using unique_ptr ?
[3]
#include <iostream>
#include<memory>
void foo(std::unique_ptr<int> i)
{
(*i)++;
}
int main ()
{
auto ptr = std::make_unique<int>(23);
foo(ptr);
cout<<*ptr<<endl;
return 0;
}
[4]
void foo(std::unique_ptr<int> i)
{
(*i)++;
cout<<" i am in foo() function"<<endl;
cout<<*i<<endl;
}
int main ()
{
auto ptr = std::make_unique<int>(23);
foo(std::move(ptr));
cout<<"After move ptr = "<<*ptr<<endl;
return 0;
}
output:
i am in foo() function
24
Segmentation fault
Note: Above program will be crashed as we are trying to access ptr which become NULL after moving it.
#include<iostream>
#include<map>
#include<memory>
using namespace std;
void foo(std::unique_ptr<int> &i)
{
(*i)++;
cout<<" i am in foo() function"<<endl;
cout<<*i<<endl;
}
int main ()
{
auto ptr = std::make_unique<int>(23);
foo(std::move(ptr));
cout<<"After move ptr = "<<*ptr<<endl;
return 0;
}
output :
compilation error
cannot bind non-const lvalue reference of type 'std::unique_ptr<int>&' to an rvalue of type 'std::remove_reference<std::unique_ptr<int>&>::type' {aka 'std::unique_ptr<int>'}
Comments
Post a Comment