I have a scenario where I often use non-pointer variables, including objects.
I want to set these variables to an existing set of data from an array, however I do not want a soft-copy, instead I want the non-pointer variable to point directly to the memory address of the other variable.
This is a simple example piece of code for my dilemma.
struct User
{
unsigned int ID;
std::string Name;
User(int id, std::string name)
{
ID = id;
Name = name;
}
};
User data[] =
{
User(2, "Jane Smith"),
};
void ChangeUser(User& user)
{
user = data[0];
}
int main()
{
User first;
ChangeUser(first);
return 0;
}
If I want a function that can change it to a new address, I can pass the non-pointer object as a pointer to an object.
void ChangeUser(User* user)
{
user = &data[0];
}
int main()
{
User first;
ChangeUser(&first);
return 0;
}
However, this doesn't change the variable outside the function, as it passes in the pointer by value. What I can do is pass in a pointer by reference, which means if I pass in a pointer, the data will be changed even after the function.
void ChangeUser(User*& user)
{
user = &data[0];
}
However, if I try with a non-pointer variable, I get this compilation error where I call the function.
error C2664: 'void ChangeUser(User *&)' : cannot convert argument 1 from 'User *' to 'User *&'
If I create a pointer variable as below, the compiler will accept it and will set the data of the pointer to the pointer of the member in the array.
However, if I have to use non-pointer variables, is there a way for me to achieve the same task? Ideally I want to be able to keep a User variable as a member of a class, so local reference variables cannot be used.