Reputation: 13651
I have the following code
class A {
A(int & r)
: i(r)
{}
A(A&& obj)
: i(obj.i)
{}
operator=(A&& obj)
{
// ?
}
int& i;
}
And imagine the following main
int main()
{
int r = 12;
int r2 = 21;
A a(r);
A b(r2);
b = std::move(a);
r = 42;
std::cout << "b.i value is " << b.i << std::endl;
}
I would like it to print out b.i value is 42
.
In short, is it possible to modify i
to make it refer to obj.i
in operator=()
?
Upvotes: 0
Views: 183
Reputation: 5116
The short answer is No.
In order to understand why the answer is no, you need to realize what a reference really is. A reference is not a pointer. In fact, a reference is not even an object: it is simply an alias for another location in memory. The standard actually says that a reference does not (need to) have an address, so it doesn't even need to exist in memory. For all you know, a reference could (in many cases) disappear completely at compile-time.
Given a reference variable, you cannot use it to refer to the reference itself. Any use of its name will refer to the memory location to which it refers. This is why you cannot create a pointer to a reference. That is, you cannot take the address of a reference. Which is good, because, as previously stated, it may not even have an address.
So, given that it doesn't necessarily have a place in memory, and you cannot refer to its value (only the value of what it refers to), you cannot change the "value" of the reference itself. This is why it is an error in C++03 to try to create a constant reference (T& const
). (In C++11, however, this is allowed because of reference collapsing, which is necessary when introducing rvalue-references)
Upvotes: 4
Reputation: 25927
Operator = is called after the constructor was called, and reference fields cannot be left uninitialized - you have to set them in class's constructors. So the answer is no. Use pointers or smart pointers instead.
Upvotes: 0