When I dereference a pointer and assign to it, it changes what the pointer points to, it doesn't call operator=
for what it points to. I made this program to prove it:
#include <iostream>
struct S
{
void operator =(int)
{ x = 5; }
operator int*()
{
return &x;
}
int x;
};
std::ostream& operator <<(std::ostream& out, S const& s)
{
return out << s.x;
}
int main()
{
S s;
int *x = s;
*x = 10;
std::cout << *x;
}
This prints 10. Doing *x = 10
doesn't modify the object x
points to. How can I make it do so? (C++11 solutions are welcome)
Your code is undefined behavior. int *x = S();
initializes x
to an address to a temporary, which gets destroyed at the end of the full expression, so *x
is illegal.
Use std::reference_wrapper
:
#include <memory>
#include <functional>
int main()
{
S s;
auto x = std::make_shared<S>(std::ref(s));
*x = 10;
std::cout << *x; // prints 5
}
The local x
variable in the main function is of type pointer to int
. The int
it is pointing to is the S::x
subobject of the S
instance, as returned by S::operator int*
. When you dereference it you get an lvalue of type int
which is still the S::x
subobject. So when you call operator=
on this lvalue int
, it dispatches to the builtin int::operator=
, not your user-defined S::operator=
.
The user-defined S::operator=
function is not "inherited" by member subobjects of a class. I think this is what is confusing you.
If you want to use the S::operator=
then you need to call it with an lvalue of type S
:
int main()
{
S s;
S *x = &s;
*x = 10;
std::cout << x->x;
}
will do what you want and call S::operator=
.
Perhaps you meant to define x of type S? There is no reason for it to call an overloaded operator when it is of type int.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.