Hello,

I'm trying to learn unique_ptr, so I'm playing with it to get some idea.

I tried to write a function that returns a unique_ptr; called the function in main(). But my code produces an error, which I'm not able to understand. Kindly help me in resolving this.

Qt Code:
  1. #include <iostream>
  2.  
  3. #include <memory>
  4.  
  5. using namespace std;
  6.  
  7. class String
  8. {
  9. string d_string;
  10. public:
  11. String() { cout << "Default ctor" << endl; }
  12. String(string const & obj) : d_string(obj) { cout << "Parameterized Ctor" << endl; }
  13. String(String && tmp) : d_string(tmp.d_string)
  14. {
  15. tmp.d_string = nullptr;
  16. cout << "Move Ctor" << endl;
  17. }
  18. String(String const & obj) : d_string(obj.d_string)
  19. {
  20. cout << "Copy Ctor" << endl;
  21. }
  22. ~String() { cout << "Dtor" << endl; }
  23. friend ostream & operator<<(ostream & out, unique_ptr<String> & obj);
  24. String & operator=(String const & rhs)
  25. {
  26. d_string = rhs.d_string;
  27. return *this;
  28. }
  29. void setVal(string const & str)
  30. {
  31. d_string = str;
  32. }
  33.  
  34. string getVal() const { return d_string; }
  35. };
  36.  
  37. // I haven't used this as it was reporting error.
  38. // So added a getVal() member function
  39. ostream & operator<<(ostream & out, unique_ptr<String> & obj)
  40. {
  41. out << obj->d_string << endl;
  42. return out;
  43. }
  44.  
  45. unique_ptr<string> && f()
  46. {
  47. unique_ptr<String> p;
  48. p->setVal(string("rahul"));
  49. return move(p);
  50. }
  51.  
  52. int main()
  53. {
  54. unique_ptr<String> ptr = f();
  55. cout << ptr->getVal() << endl;
  56. }
To copy to clipboard, switch view to plain text mode 

And the error is
Qt Code:
  1. main.cpp: In function ‘std::unique_ptr<std::__cxx11::basic_string<char> >&& f()’:
  2. main.cpp:47:16: error: invalid initialization of reference of type ‘std::unique_ptr<std::__cxx11::basic_string<char> >&&’ from expression of type ‘std::remove_reference<std::unique_ptr<String>&>::type {aka std::unique_ptr<String>}’
  3. return move(p);
  4. ~~~~^~~
  5. main.cpp: In function ‘int main()’:
  6. main.cpp:52:31: error: conversion from ‘std::unique_ptr<std::__cxx11::basic_string<char> >’ to non-scalar type ‘std::unique_ptr<String>’ requested
  7. unique_ptr<String> ptr = f();
  8. ~^~
  9. make: *** [Makefile:6: main.o] Error 1
To copy to clipboard, switch view to plain text mode 


I have no idea what's happening. Please guide me if my implementation is wrong. Thanks.