Can anyone explain the logic behind structs being allowed neither memeber
initialisers or default constructors.
Doesn't this just encourage developers to create constructors with dummy
arguments?
Thanks in advance,
Jasper Kent. 19 2127
IMO:
In C# we come to expect all value types to default to a
zero-initialized instance. So if I wrote:
static void Main(string[] args)
{
int x = new int();
Console.WriteLi ne(x);
}
and a "2" appeared in the console window, I'd wonder if I regressed to
C++ where such things can occur. The spec guarantees this won't
happen. Since a struct is also a value type, it would be just as
strange to see a "2" appear in the following:
class Class1
{
[STAThread]
static void Main(string[] args)
{
Foo f = new Foo();
Console.WriteLi ne(f.x);
}
}
struct Foo
{
public int x;
}
To preserve the correct behavior then, a struct cannot explicitly
declare a default constructor, and (as you probably noticed), you
can't use an instance field initializer either.
--
Scott http://www.OdeToCode.com
On Fri, 30 Apr 2004 13:17:56 +0100, "Jasper Kent"
<ja*********@nt lworld.com> wrote: Can anyone explain the logic behind structs being allowed neither memeber initialisers or default constructors.
Doesn't this just encourage developers to create constructors with dummy arguments?
Thanks in advance,
Jasper Kent.
That's kind of a bootstrap argument, and I don't buy it.
In any O-O language we excpect any type to default to a sensible value.For
exanple:
struct PositiveInteger {...}
....
PositiveInteger val = new PositiveInteger ();
Console.WriteLi ne (val.ToString ()) ; // We'd be surpsrised by zero here
And anyway, whatever the argument, why is it different for a struct and a
class?
"Scott Allen" <bitmask@[nospam].fred.net> wrote in message
news:6l******** *************** *********@4ax.c om... IMO:
In C# we come to expect all value types to default to a zero-initialized instance. So if I wrote:
static void Main(string[] args) { int x = new int(); Console.WriteLi ne(x);
}
and a "2" appeared in the console window, I'd wonder if I regressed to C++ where such things can occur. The spec guarantees this won't happen. Since a struct is also a value type, it would be just as strange to see a "2" appear in the following:
class Class1 { [STAThread] static void Main(string[] args) { Foo f = new Foo(); Console.WriteLi ne(f.x);
} } struct Foo { public int x; }
To preserve the correct behavior then, a struct cannot explicitly declare a default constructor, and (as you probably noticed), you can't use an instance field initializer either.
-- Scott http://www.OdeToCode.com
On Fri, 30 Apr 2004 13:17:56 +0100, "Jasper Kent" <ja*********@nt lworld.com> wrote:
Can anyone explain the logic behind structs being allowed neither memeber initialisers or default constructors.
Doesn't this just encourage developers to create constructors with dummy arguments?
Thanks in advance,
Jasper Kent.
Jasper Kent wrote: That's kind of a bootstrap argument, and I don't buy it.
In any O-O language we excpect any type to default to a sensible value.For exanple:
struct PositiveInteger {...}
...
PositiveInteger val = new PositiveInteger ();
Console.WriteLi ne (val.ToString ()) ; // We'd be surpsrised by zero here
And anyway, whatever the argument, why is it different for a struct and a class?
Here's a cut-n-paste from an entry in Stan Lippmann's weblog that I
recently read (thing1 is the first version of MC++, thing2 is the
revised version of MC++):
=============== =============== =============== =============
Another difference with a value type between thing1 and thing2 is the
removal of support for a default constructor. [It has been explained to
me that this is because there are instances in which the CLR can create
an instance of the value type without invoking the associated default
constructor. That is, the thing1 addition of support of a default
constructor within a value type cannot be guaranteed. Given that absence
of guarantee, it was felt to be better to drop the support altogether
rather than have it be non-deterministic in its application.]
This is not as bad as it might seem because each object of a value type
is zeroed out automatically, so that the members of a local instance are
not undefined. This also meant that in thing1 a default constructor that
simply zeroed out its members was being redundant. The problem is that a
non-trivial default constructor in a thing1 program has no mechanical
mapping to thing2. The code within the constructor will need to be
migrated into a named init function that would then be explicitly
invoked by the user.
=============== =============== =============== =============
You can read the full entry here: http://blogs.msdn.com/slippman/archi.../26/80505.aspx "Scott Allen" <bitmask@[nospam].fred.net> wrote in message news:6l******** *************** *********@4ax.c om...
IMO:
In C# we come to expect all value types to default to a zero-initialized instance. So if I wrote:
static void Main(string[] args) { int x = new int(); Console.WriteLi ne(x);
}
and a "2" appeared in the console window, I'd wonder if I regressed to C++ where such things can occur. The spec guarantees this won't happen. Since a struct is also a value type, it would be just as strange to see a "2" appear in the following:
class Class1 { [STAThread] static void Main(string[] args) { Foo f = new Foo(); Console.WriteLi ne(f.x);
} } struct Foo { public int x; }
To preserve the correct behavior then, a struct cannot explicitly declare a default constructor, and (as you probably noticed), you can't use an instance field initializer either.
-- Scott http://www.OdeToCode.com
On Fri, 30 Apr 2004 13:17:56 +0100, "Jasper Kent" <ja*********@ ntlworld.com> wrote:
Can anyone explain the logic behind structs being allowed neither memeber initialise rs or default constructors.
Doesn't this just encourage developers to create constructors with dummy arguments?
Thanks in advance,
Jasper Kent.
--
mikeb
> > In any O-O language we excpect any type to default to a sensible
value.For exanple:
struct PositiveInteger {...}
PositiveInteger val = new PositiveInteger ();
Console.WriteLi ne (val.ToString ()) ; // We'd be surpsrised by zero
here And anyway, whatever the argument, why is it different for a struct and
a class?
Here's a cut-n-paste from an entry in Stan Lippmann's weblog that I recently read (thing1 is the first version of MC++, thing2 is the revised version of MC++):
=============== =============== =============== ============= Another difference with a value type between thing1 and thing2 is the removal of support for a default constructor. [It has been explained to me that this is because there are instances in which the CLR can create an instance of the value type without invoking the associated default constructor. That is, the thing1 addition of support of a default constructor within a value type cannot be guaranteed. Given that absence of guarantee, it was felt to be better to drop the support altogether rather than have it be non-deterministic in its application.]
This is not as bad as it might seem because each object of a value type is zeroed out automatically, so that the members of a local instance are not undefined. This also meant that in thing1 a default constructor that simply zeroed out its members was being redundant. The problem is that a non-trivial default constructor in a thing1 program has no mechanical mapping to thing2. The code within the constructor will need to be migrated into a named init function that would then be explicitly invoked by the user.
Iam not sure what this text is trying to tell use but we can create a struct
without calling a ctor:
Point p;
p.X=100;
p.Y=120;
in this case the compiler enforces that each field is initialized before
first access.
--
cody
[Freeware, Games and Humor] www.deutronium.de.vu || www.deutronium.tk
"cody" <pl************ *************@g mx.de> wrote in message
news:us******** ******@TK2MSFTN GP11.phx.gbl... > In any O-O language we excpect any type to default to a sensible value.For > exanple: > > struct PositiveInteger {...} > > PositiveInteger val = new PositiveInteger (); > > Console.WriteLi ne (val.ToString ()) ; // We'd be surpsrised by zero here > > And anyway, whatever the argument, why is it different for a struct and a > class? Here's a cut-n-paste from an entry in Stan Lippmann's weblog that I recently read (thing1 is the first version of MC++, thing2 is the revised version of MC++):
=============== =============== =============== ============= Another difference with a value type between thing1 and thing2 is the removal of support for a default constructor. [It has been explained to me that this is because there are instances in which the CLR can create an instance of the value type without invoking the associated default constructor. That is, the thing1 addition of support of a default constructor within a value type cannot be guaranteed. Given that absence of guarantee, it was felt to be better to drop the support altogether rather than have it be non-deterministic in its application.]
This is not as bad as it might seem because each object of a value type is zeroed out automatically, so that the members of a local instance are not undefined. This also meant that in thing1 a default constructor that simply zeroed out its members was being redundant. The problem is that a non-trivial default constructor in a thing1 program has no mechanical mapping to thing2. The code within the constructor will need to be migrated into a named init function that would then be explicitly invoked by the user.
Iam not sure what this text is trying to tell use but we can create a struct without calling a ctor:
Point p; p.X=100; p.Y=120;
in this case the compiler enforces that each field is initialized before first access.
Thats actually the point of the text. Structs don't support default
constructors, but instead are created zero'd out. If the compiler decides to
mantain flow information and ensure that you set all variables, thats good
and helpful, but its not strictly nessecery, IIRC.
-- cody
[Freeware, Games and Humor] www.deutronium.de.vu || www.deutronium.tk
cody wrote: In any O-O language we excpect any type to default to a sensible value.For exanple:
struct PositiveInteger {...}
PositiveInte ger val = new PositiveInteger ();
Console.Writ eLine (val.ToString ()) ; // We'd be surpsrised by zero here And anyway, whatever the argument, why is it different for a struct and a class?
Here's a cut-n-paste from an entry in Stan Lippmann's weblog that I recently read (thing1 is the first version of MC++, thing2 is the revised version of MC++):
============= =============== =============== =============== Another difference with a value type between thing1 and thing2 is the removal of support for a default constructor. [It has been explained to me that this is because there are instances in which the CLR can create an instance of the value type without invoking the associated default constructor . That is, the thing1 addition of support of a default constructor within a value type cannot be guaranteed. Given that absence of guarantee, it was felt to be better to drop the support altogether rather than have it be non-deterministic in its application.]
This is not as bad as it might seem because each object of a value type is zeroed out automatically, so that the members of a local instance are not undefined. This also meant that in thing1 a default constructor that simply zeroed out its members was being redundant. The problem is that a non-trivial default constructor in a thing1 program has no mechanical mapping to thing2. The code within the constructor will need to be migrated into a named init function that would then be explicitly invoked by the user.
Iam not sure what this text is trying to tell use but we can create a struct without calling a ctor:
Point p; p.X=100; p.Y=120;
in this case the compiler enforces that each field is initialized before first access.
I'm not an very familiar with MC++, but apparently in the current
version it supports specifying a default constructor for value types.
Here's a line taken from the docs on MC++ __value classes:
-----------------------------------
If no default constructor is defined for a __value class, all of its
data members are initialized to zero by default.
-----------------------------------
I believe that Stan is saying in his weblog is that they are removing
support for default constructors on __value classes in MC++ for the
reason he stated (if you have a copy of Whidbey, you could look there to
verify this - I'm even less familiar with MC++ on Whidbey).
Now, why the CLR might not invoke a default constructor for a value type
is another question. I assume it's because the CLR folks didn't see
it as an important feature (Stan mentions that "this is not as bad as it
seems...") and to allow some optimizations, but I'm just guessing.
--
mikeb
> > Iam not sure what this text is trying to tell use but we can create a struct without calling a ctor:
Point p; p.X=100; p.Y=120;
in this case the compiler enforces that each field is initialized before first access. Thats actually the point of the text. Structs don't support default constructors, but instead are created zero'd out. If the compiler decides
to mantain flow information and ensure that you set all variables, thats good and helpful, but its not strictly nessecery, IIRC.
I don't believe that fields are zeroed out automatically if you don't call
the ctor.
If so, the line
Point p = new Point();
would zero out all fields twice.
--
cody
[Freeware, Games and Humor] www.deutronium.de.vu || www.deutronium.tk
"cody" <pl************ *************@g mx.de> wrote in message
news:%2******** *******@TK2MSFT NGP10.phx.gbl.. .
I don't believe that fields are zeroed out automatically if you don't call the ctor. If so, the line
Point p = new Point();
would zero out all fields twice.
A struct is created, generally, in null memory. I'm pretty sure the .NET
memory model ensures that a variable created on the stack retains a zero
value, even if its unassigned. I could be wrong but it would seem unlikely.
The difference in
Point p;
and
Point p = new Point();
is new Point() issues an initobj instruction in IL. That initobj instruction
should zero memory in most case(structs written in other languages may not
zero, AFAICT), however the original structure on the stack should already be
zeroed(someone correct me if I am wrong, I'm pretty sure I'm not though).
Your example does indeed zero twice: once explicitly(duri ng new Point()) and
once implicitly at stack construction. In that case I would expect the JIT
to effectivly remove the initobj instruction whenever it knows that the
initalization is pointless. new Point() would be more valuable when the
value in p has been used. It would clear that value back out.
As a matter of technical fact, I don't believe that its required to init a
struct before use. C# tends to disallow it, however, under assignment
rules(I've run into one situation where it seems to be allowed, which I have
to check on). I think that is more for the purposes of correct, well though
out code more so than it is a problem with the underlying platform. -- cody
[Freeware, Games and Humor] www.deutronium.de.vu || www.deutronium.tk
> A struct is created, generally, in null memory. I'm pretty sure the .NET memory model ensures that a variable created on the stack retains a zero value, even if its unassigned. I could be wrong but it would seem
unlikely.
No. Locals and structs are created on the stack which does *not* contain
zeros, but instead data of previous method invocations.
If a method returns it would have to overwrite the stack with zeros to clean
up, if you want the behavour that every struct is generated in "null
memory".
C# forces you to initialize *every* local variable completely before first
use. In the case of structs a ctor call is not needed if you assign all
fields manually.
The difference in Point p;
and Point p = new Point();
is new Point() issues an initobj instruction in IL. That initobj
instruction should zero memory in most case(structs written in other languages may not zero, AFAICT), however the original structure on the stack should already
be zeroed(someone correct me if I am wrong, I'm pretty sure I'm not though). Your example does indeed zero twice: once explicitly(duri ng new Point())
and once implicitly at stack construction. In that case I would expect the JIT to effectivly remove the initobj instruction whenever it knows that the initalization is pointless. new Point() would be more valuable when the value in p has been used. It would clear that value back out.
Think: Would the initobj call would make sense in any circumstance when
structs would already zeroed out a creation time?
As a matter of technical fact, I don't believe that its required to init a struct before use. C# tends to disallow it, however, under assignment rules(I've run into one situation where it seems to be allowed, which I
have to check on). I think that is more for the purposes of correct, well
though out code more so than it is a problem with the underlying platform.
Which situation? I'd like to hear.
--
cody
Freeware Tools, Games and Humour http://www.deutronium.de.vu || http://www.deutronium.tk This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Paminu |
last post by:
Why make an array of pointers to structs, when it is possible to just make
an array of structs?
I have this struct:
struct test {
int a;
int b;
|
by: Bilgehan.Balban |
last post by:
Hi,
I am currently brushing up my c++ knowledge and I would like to ask you
about the differences between classes and C structs, in the
function/method perspective.
1) Is it correct to say that, a structure definition that includes
function pointers only defines the function prototypes to be used with
them, but not the actual implementations, whereas in C++, member
functions cannot be changed *unless* virtual functions are used, or the
|
by: Marty |
last post by:
I am new to C# and to structs so this could be easy or just not
possible.
I have a struct defined called Branch
If I use Branch myBranch = new Branch(i); // everything works
If I use Branch (myBranch + x) = new Branch(i); // it doesn't
x is a loop iterator, i is an int for the constructor to define an
array.
What am I doing wrong here.
|
by: Dom |
last post by:
I'm really confused by the difference between a Struct and a Class?
Sometimes, I want just a group of fields to go together. A Class
without methods seems wrong, in that it carries too much overhead (I
think). A Struct seems more appropriate. At least it is what I would
have used in other languages. But since a Struct *can* hold methods,
I wander if I am saving anything. If not, why use it?
|
by: JohnQ |
last post by:
Are a default constructor, destructor, copy constructor and assignment
operator generated by the compiler for a struct if they are not explicitely
defined?
I think the answer is yes, because "there is no difference between a struct
and a class except the public/private access specification" (and a few minor
other things). When I create a class, I always start by declaring the
default constructor, copy constructor and assignment operator...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |