Thread: new Struct?

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    203

    new Struct?

    I was in a discussion about using new on structs and no one was able to be exactly sure what happens. What does it do? Does it allocate a new block of memory every time you call new on an existing struct variable or just set the values to default? The MSDN isn't very clear on this.

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    49
    I don't think structures can be instantiated, only classes. Thtats why you want to use a class over a structure.

  3. #3
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    They can. They could even in C.
    When you call new it expects a pointer, not a variable. It returns a memory location allocated.
    If you have
    Code:
    str* ptr = new str;
    ptr = new str;
    Then you will allocate a memory block and assign it to ptr. Then assign another memory block and assign it to ptr. You would create a memory leak (of course) since the first memory block couldn't be referenced.

    Structs are pretty much the same as classes in these situations. The variables will be set as instructed in the constructor, nothing else.

    So, yes, it allocates a new block of memory every time. If you have code you can post it or some sample one.

  4. #4
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Quote Originally Posted by C_ntua View Post
    So, yes, it allocates a new block of memory every time.
    Really? Post your source.

    Consider the follow the code:
    Code:
    struct MyPoint
    {
        public int X;
        public int Y;
    
        public MyPoint(int x, int y)
        {
            X = x;
            Y = y;
        }
    
    }
    
    static void Main(string[] args)
    {
        MyPoint p = new MyPoint(1, 2);
        p = new MyPoint(3, 4); //This is the important line
        //...
    }
    Thinking through the problem, the compiler could be implemented in one of two ways:
    1. Create yet another MyPoint initialized with 3,4. Use the default assignment to copy these values into p. In this case, a MyPoint copy sticks around for a very short amount of time and will be quickly GC'ed, but it's still a waste.
    2. Note that this is a struct and simply run the initialization code from the constructor.
    There's absolutely no reason to use more memory just to re-initialize a struct since structs are copied by-value. If this is obvious to me with just a few minutes of thought, then surely it was obvious to the compiler writers. I'd have to hope it was done the second way; I'm not sure how to test to see if it is.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  5. #5
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Quote Originally Posted by pianorain View Post
    Really? Post your source.
    Sorry, thought this was C++!

  6. #6
    Registered User
    Join Date
    Mar 2002
    Posts
    203
    Is there a way to show that it does this? I have VS 2008 pro, VS 2010 ultimate, and various VS team editions available to me.
    Last edited by Syneris; 09-04-2010 at 01:55 PM. Reason: compiler detail

  7. #7
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Reading more about structs, I see they are actually Value Types. Thus they should be allocated on the stack not on the heap (except if it is more complicated than that).

    Froms MSDN:
    When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

    The situation of using new after the struct is created doesn't seem to be covered. But it doesn't make sense to re-create it since it is on the stack so I am pretty sure it will simply initialize it again.

  8. #8
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    If you think of structs as data blocks in C# and classes as data plus behavior it is much simpler to distinguish between them. You do not need to instantiate structs with new.

  9. #9
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Quote Originally Posted by Bubba View Post
    If you think of structs as data blocks in C# and classes as data plus behavior it is much simpler to distinguish between them. You do not need to instantiate structs with new.
    I would say that it is not a bad idea though to keep a specific syntax. For example you might want to switch a struct with a class later on. Since it is specified that all the links have to be instantiated new is likely to be your most common way to create+initialize a struct. And a good way to re-initialize the struct.

    In a few words the syntax is kind of nice, since it doesn't differ from the most common syntax of instantiating classes. You don't have to worry if it is a class or a struct, but for optimizations for example you can still use a struct, so you could turn a class into a struct later on, depending of course the use.

  10. #10
    Registered User
    Join Date
    Mar 2002
    Posts
    203
    Most the people i've been talking to are surprised that structs are value types created on the stack. However, they still insist that more memory is allocated each time new is used and that the GC takes care of the old memory. If new memory is not allocated for each successive call to new on the same variable, how can I prove it?

    Also, Is there any difference when calling new on a struct without use of a variable?
    IE: (Vector2 is an XNA struct)
    Code:
    Vector2 v;
    v.X = 1; //1 just because it isn't 0
    v.Y = 1;
    VectorMethod(v);
    vs
    Code:
    Vector2 v = new Vector2(1,1);
    VectorMethod(v);
    vs
    Code:
    VectorMethod(new Vector2(1,1));

  11. #11
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    I would say no there is no difference on the first two, in the sense that you cannot use a struct unless you initialize all its fields. So you are actually doing what new does.

    There are more chances for the compiler to make optimizations when you use the "new" since it is more direct and more compact. But your example is mostly what the compiler would do anyway, but you cannot know for sure (unless you find out).

    The last one saves allocating one extra variable, which might be significant (in a critical section of course). Again, the compiler might make that optimization itself (maybe not).

    The Garbage Collector doesn't take care of memory in the stack. I mean, why would it? The stack gets deallocated when the function ends, that's the point of it. C# specifies that it used two types: reference and value. I haven't read anymore that structs are a special one or something in between. So writing a struct with 4 int is the same as allocating 4 int on the stack, like
    Code:
    int field1;
    int field2;
    int field3;
    int field4;
    Now you may ask what happens when yo do
    Code:
    point1 = point2;
    Well, all the fields are copied. Like a value type. You see despite the syntax, a struct works like a normal value type. A struct with 4 int would be like a 16byte variable with some syntax to get the correct part of it, initialize it and all the other stuff.

    So, what happens if you call
    Code:
    Point p = new Point(10, 10);
    For those that support that it allocates more space, it would allocate space, give the values in the constructor, copy the values to struct p and then de-allocate that space. Which is obviously stupid to do. So it won't do it.

    Why isn't this clearly specified? Well, because I guess as stated above they don't really want you to go to all these details about it. What if it was stupid and it allocated memory? It is not wrong as a concept, the result is the same. That is what the language cares about on the result not the how it is done, except if the how is specified in the language standards.

  12. #12
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    I think we are making a mountain out of molehill here. How the language allocates is really not something you should concern yourself with. Whether or not it allocates I believe is quite clear from a struct's usage and behavior as it relates to C#. If you do not call new then obviously the GC isn't doing anything with it....or you can think of it that way. Whether or not it does under the hood is anyone's guess but as long as my struct is valid and I can use it...from a C# standpoint I really don't care.

    If you are looking to manage memory or know at all times the memory footprint of your application then I would venture to say you should use a language like C or C++. C# is designed so the programmer doesn't have to worry about all of that and when you try to worry about it you will end up right back where you started.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. casting struct to struct
    By klmdb in forum C Programming
    Replies: 6
    Last Post: 08-14-2010, 02:29 PM
  2. Help me please.
    By yann in forum C Programming
    Replies: 15
    Last Post: 09-29-2009, 09:04 PM
  3. help with structs and malloc!
    By coni in forum C Programming
    Replies: 20
    Last Post: 09-14-2009, 05:38 PM
  4. Replies: 1
    Last Post: 12-03-2008, 03:10 AM
  5. Replies: 10
    Last Post: 05-18-2006, 11:23 PM