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;
}
6
  • Welcome to stackoverflow.com. Please take some time to read the help pages, especially the sections named "What topics can I ask about here?" and "What types of questions should I avoid asking?". Also please take the tour and read about how to ask good questions. Lastly please read this question checklist. Commented Apr 25, 2019 at 7: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 &). Commented Apr 25, 2019 at 7:23
  • adding to @darune's answer you have to use the following: std::unique_ptr<int> a = std::make_unique<int>(); abc(a); you can't initialize smart pointers like std::unique_ptr<int> a(new int); Commented Apr 25, 2019 at 7:24
  • 1
    @shesharp That's incorrect. Especially considering that std::make_unique wasn't introduced until the C++14 standard, while std::unique_ptr was introduced in the C++11 standard. Commented Apr 25, 2019 at 7:27
  • @Someprogrammerdude thanks for pointing that out! I thought error was due to std::unique_ptr<int> a(new int); Im used to using it with make_unique i thought it was wrong. Commented Apr 25, 2019 at 7:34

1 Answer 1

1

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

int abc(const std::unique_ptr<int>& a)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.