Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ method that can/cannot return a struct

Tags:

c++

struct

I have a C++ struct and a method:

struct Account
{
    unsigned int id;
    string username;
    ...
};


Account GetAccountById(unsigned int id) const { }

I can return an Account struct if the account exists, but what to do if there's no account?

I thought of having:

  • An "is valid" flag on the struct (so an empty one can be returned, with that set to false)
  • An additional "is valid" pointer (const string &id, int *is_ok) that's set if the output is valid
  • Returning an Account* instead, and returning either a pointer to a struct, or NULL if it doesn't exist?

Is there a best way of doing this?

like image 756
Lucky5 Avatar asked Dec 13 '10 15:12

Lucky5


3 Answers

You forgot the most obvious one, in C++:

bool GetAccountById(unsigned int id, Account& account);

Return true and fill in the provided reference if the account exists, else return false.

It might also be convenient to use the fact that pointers can be null, and having:

bool GetAccountById(unsigned int id, Account* account);

That could be defined to return true if the account id exists, but only (of course) to fill in the provided account if the pointer is non-null. Sometimes it's handy to be able to test for existance, and this saves having to have a dedicated method for only that purpose.

It's a matter of taste what you prefer having.

like image 99
unwind Avatar answered Oct 27 '22 16:10

unwind


From the options given I would return Account*. But returning pointer may have some bad side effect on the interface.

Another possibility is to throw an exception when there is no such account. You may also try boost::optional.

like image 44
Juraj Blaho Avatar answered Oct 27 '22 16:10

Juraj Blaho


You could also try the null object pattern.

like image 22
Goz Avatar answered Oct 27 '22 16:10

Goz