1
votes

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.

1
"However, if I try with a non-pointer variable, I get this compilation error where I call the function." Please post code leading to this error... - jpo38
@jpo38 They did. - user0042
"I want the non-pointer variable to point directly to the memory address of the other variable." That sounds kind of impossible. - juanchopanza
"I want a function that can change it to a new address" You can't change the address of a stack-allocated object. - emlai

1 Answers

1
votes

The code

User first;
ChangeUser(&first);

effectively passes a const User*& pointer reference (rvalue) to the function (which want's a non-const lvalue), hence the error.

You cannot change the address of an already allocated object.