Search code examples
c#c++memory-managementcil

How to reinitialize an object in C# at the same memory location in terms of C++ (or is it done automatically)?


In C++ I used constructions like

#include "stdafx.h"
#include "TestStaticPointer.h"

MyClass* MyClass::myStaticPointer;

int main()
{
    ProgrammStart();

    return 0;
}

void ProgrammStart()
{
    MyClass::myStaticPointer = new MyClass();
}

void SomeProgrammPlace()
{
    *MyClass::myStaticPointer = MyClass();
}

So that I allocated memory just once in ProgrammStart() and then I used the same memory location to reinitialize my static pointer (without reallocating by 'new'), I just used construction "= MyClass();".

How can I do this in C#? Does the IL take all the work about allocations? Does 'new' always mean a 'new' memory location (not the same place in memory) in terms of C++?


Solution

  • First of all, you haven't re-initialized anything. What you've done here is assignment. You created a new MyClass object and modified the state of the existing MyClass object to be the same as the new one by calling its assignment operator.

    The same thing will happen when you assign to a struct in C#:

    class Program
    {
        static void Main(string[] args)
        {
            MyStruct mc = new MyStruct(10);
    
            // Will print 10
            Console.WriteLine(mc.i);
            unsafe
            {
                MyStruct* pmc = &mc;
                // Will print the address of mc
                Console.WriteLine((IntPtr)pmc);
            }
    
            // Assign to mc
            mc = new MyStruct(20);
    
            // Will print 20; mc was modified
            Console.WriteLine(mc.i);
            unsafe
            {
                MyStruct* p = &mc;
                // Will print the same address as above.
                // mc was modified in place
                // because structs have value semantics
                Console.WriteLine((IntPtr)p);
            }
        }
    }
    
    struct MyStruct
    {
        public MyStruct(int i)
        {
            this.i = i;
        }
        public int i;
    }