user16078551
user16078551

Reputation:

From (pointer to a list of pointer to class) to list of classes

I have this function where I need to return const std::list<Album> , and what I have is std::list<Album*>*.

How can I convert the first type to the second type?

const std::list<Album> DatabaseAccess::getAlbums()
{
    char* sqlStatement = "SELECT * FROM Albums;";
    char* errMessage = nullptr;

    std::list<Album*>* data = new std::list<Album*>;

    sqlite3_exec(this->_DataBase, sqlStatement, Album::callback, data, &errMessage);

    return  ; // ?
}

EDIT:

Will this work?

std::list<Album> casted_list;

for (auto i = data->begin(); i != data->end(); i++)
{
    casted_list.push_back(*(*i));
}

Upvotes: 0

Views: 86

Answers (1)

Galik
Galik

Reputation: 48625

It looks like you are using a lot of unnecessary pointers and dynamic allocation in your code. It is hard to be sure without seeing what your Album objects look like but I would probably do something like this:

class Album
{
public:
    Album(std::string const& name): m_name(name) {}

    static int callback(void* uptr, int no_of_cols, char** results, char** column_names)
    {
        // cast our void* to what we are working with
        std::list<Album>& albums = *reinterpret_cast<std::list<Album>*>(uptr);

        // pass the Album's constructor arguments to emplace(...)
        albums.emplace_back(results[0]);

        return {};
    }

private:
    std::string m_name;
};

class DatabaseAccess
{
public:
    std::list<Album> getAlbums();

private:
    sqlite3* _DataBase = nullptr;
};

std::list<Album> DatabaseAccess::getAlbums()
{
    char const* sqlStatement = "SELECT * FROM Albums;";
    char* errMessage = nullptr;

    // No need to get into pointers here
    std::list<Album> data;

    // send the address of data to the callback function
    sqlite3_exec(this->_DataBase, sqlStatement, Album::callback, &data, &errMessage);

    return  data; // then just return your list
}

As far as I can tell you don't really need to create anything other than a std::list<Album> (your desired return type) to begin with and avoid all the pointers.

Upvotes: 1

Related Questions