1

How do I pass the unique_ptr in the below code? This code does not compile.

int abc(int*& a)
{  
    return 1;
}

int main()
{
    std::cout<<"Hello World";
    std::unique_ptr<int> a(new int); 
    abc(a.get());
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Welcome to stackoverflow.com. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Lastly please read [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Apr 25 '19 at 07:19
  • `unique_ptr::get` returns raw pointer by value, you cannot bind Rvalue (temporary object) - `a.get()` to non-const Lvalue reference. Change signature of `abc` to `abc(int*)` or `abc(int* const &)`. – rafix07 Apr 25 '19 at 07:23
  • adding to @darune's answer you have to use the following: std::unique_ptr a = std::make_unique(); abc(a); you can't initialize smart pointers like std::unique_ptr a(new int); – shesharp Apr 25 '19 at 07:24
  • 1
    @shesharp That's incorrect. Especially considering that [`std::make_unique`](https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique) wasn't introduced until the C++14 standard, while [`std::unique_ptr`](https://en.cppreference.com/w/cpp/memory/unique_ptr) was introduced in the C++11 standard. – Some programmer dude Apr 25 '19 at 07:27
  • @Someprogrammerdude thanks for pointing that out! I thought error was due to std::unique_ptr a(new int); Im used to using it with make_unique i thought it was wrong. – shesharp Apr 25 '19 at 07:34
  • @shesharp `std::unique_ptr` has a constructor that takes a raw pointer as input. It takes ownership of the memory being pointed to – Remy Lebeau Apr 25 '19 at 08:33

1 Answers1

0

You may pass it by const reference or reference for example:

int abc(const std::unique_ptr<int>& a)
darune
  • 10,480
  • 2
  • 24
  • 62