Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Return C++11 std::array

I have some code like that

#define SIZE 10
Class User
{
public:
    std::array<Account, SIZE> getListAccount()
    {
         return listAccount;
    }
private:
    std::array<Account, SIZE> listAccount
}

Class Account
{
public:
    void setUserName(std::string newUSN)
    {
        userName=newUSN;
    }
private:
    string userName;
    string password;
}


int main()
{
     User xxx(.......);
     xxx.getListAccount()[1].setUserName("abc");    // It doesn't effect
     return 0;
}

Why doesn't the setUserName() function call in main change the name in my xxx User?

By the way:

  • I'm using std::array because I want to save data in binary file
  • In my actual code, I user char [], not string
like image 929
lh84 Avatar asked Jun 05 '26 15:06

lh84


1 Answers

Return a reference to the list instead

std::array<Account, SIZE> & // << Note the &
User::getListAccount();

Or better, don't expose the internal structure

Account&
User::getUser(size_t n) 
{
    return listAccount[n];
}
like image 120
mbschenkel Avatar answered Jun 08 '26 09:06

mbschenkel