Create an object whose state changes on assignment
C++
This is trivial using the right tools.
#include <iostream>
using namespace std;
class Obj {
public:
int state;
Obj& operator= (Obj& foo) {
foo.state++;
this->state = foo.state - 2;
return *this;
}
};
int main() {
Obj a, b, c, d;
a.state = 3;
b.state = 4;
cout << a.state << " " << b.state << "\n";
c = a;
d = b;
cout << a.state << " " << b.state << " " << c.state << " " << d.state << "\n";
return 0;
}
Output:
3 4
4 5 2 3
PHP (debug build, >= 5.4)
We use refcount of the object in a getter. (So, by the assignment, refcount increases and value changes)
class State {
public function __get($arg) {
ob_start();
debug_zval_dump($this); // e.g. "object(State)#1 (0) refcount(6)"
return ob_get_clean()[29];
}
}
$obj = new State;
var_dump($obj->state);
$a = $obj;
var_dump($obj->state);
C#
Two simple options:
class Obj
{
public int state;
public static implicit operator int(Obj o)
{
return o.state++;
}
}
static int LValueI;
static Obj LValueM { set { value.state++; } }
static void Main()
{
var obj = new Obj { state = 1 };
LValueI = obj;
Console.WriteLine(obj.state); //2, caused by the implicit cast.
LValueM = obj;
Console.WriteLine(obj.state); //3, caused by the property setter.
Console.ReadLine();
}
Or we could simply write to the same memory:
[StructLayoutAttribute(LayoutKind.Explicit)]
class Program
{
[FieldOffset(0)]
int state = 1;
[FieldOffset(1)]
int LValue;
void Test()
{
var obj = this;
Console.WriteLine(state); //1
LValue = state;
Console.WriteLine(state); //257
Console.ReadLine();
}
static void Main() { new Program().Test(); }
}