C ++ - Returns C ++ 11 std :: array
I have a code like
#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 setUserName()
doesn't the function call basically change the name in my xxx
User?
By the way:
- I am using
std::array
because I want to store the data in a binary file - In my actual code, I am user char [], not a string
+3
source to share
2 answers
std::array<Account, SIZE> getListAccount() const {
return listAccount;
}
returns a copy of the array.
std::array<Account, SIZE>& getListAccount() {
return listAccount;
}
std::array<Account, SIZE> const& getListAccount() const {
return listAccount;
}
returns a reference to an array.
template<class T>
struct span_t {
T* b = 0; T* e = 0;
span_t()=default;
span_t(T* s, T* f):b(s),e(f){}
span_t(T* s, std::size_t l):span_t(s, s+l){}
T* begin() const{ return b; }
T* end() const{ return e; }
T& operator[](std::size_t i)const{ return begin()[i]; }
std::size_t size() const { return end()-begin(); }
bool empty() const { return begin()==end(); }
};
span_t<Account> getListAccount() {
return {listAccount.data(), listAccount.size()};
}
span_t<const Account> getListAccount() const {
return {listAccount.data(), listAccount.size()};
}
this returns a wrapper around a pair of pointers that represent a contiguous range of accounts without exposing the underlying data structure used to store the accounts.
Of these three, I would use span_t
. It has zero overhead and hides information that the client has little interest in.
0
source to share