0

In this code getDatabase function is 3rd party and I can't change it. Inside main function I have used shared_ptr. So there is a requirement I have to pass a Database* to the getDatabase function by reference. How can I achieve this?

 #include <iostream>
 #include <memory>

 class Database
 {
 };

 void getDatabase(Database*& pDb)
 {
     pDb = createNewDatabase();
 }

 int main()
 {
     std::shared_ptr<Database> pDb=NULL;
     getDatabase(pDb.get()); // Here is the issue pDb.get() doesn't do what I need   
     return 0;
 }
4
  • 1
    Why not first create a raw pointer, call the API, then construct the smart pointer on the raw pointer?
    – A.S.H
    Commented Nov 13, 2015 at 4:25
  • I know there can be multiple workarounds. But here I would like to know is there a direct way to pass reference to pointer managed by std::shared_ptr. Hope you understand my point Commented Nov 13, 2015 at 5:01
  • 1
    If shared_ptr was allowed to provide a non-const reference (lvalue) to its embedded raw pointer, we would not call it a smart pointer
    – A.S.H
    Commented Nov 13, 2015 at 5:06
  • @ASH: plus 1 for point of view :) Commented Nov 16, 2015 at 1:50

1 Answer 1

1

shared_ptr::get returns the managed pointer by value, so you can't bind the return value to a non-const reference.

The way to get around this is to first use a raw pointer to create the database, and then transfer ownership to the shared_ptr. You can optionally wrap that code in your own overload of getDatabase() to keep your call site clean.

void getDatabase(Database*& pDb)
{
    pDb = createNewDatabase();
}

std::shared_ptr<Database> getDatabase()
{
    Database *db = nullptr;
    getDatabase(db);
    return std::shared_ptr<Database>{db};
}

int main()
{
    std::shared_ptr<Database> pDb{getDatabase()};
}
3
  • + for the idea of overloading the function.
    – A.S.H
    Commented Nov 13, 2015 at 4:30
  • I agree for your workaround. But actually my question was is there a way to directly pass the reference to the pointer inside the smart pointer. Commented Nov 13, 2015 at 4:59
  • @NayanaAdassuriya There isn't, that's why I posted the workaround
    – Praetorian
    Commented Nov 13, 2015 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.