Setting data members in an array
Is there a way I can set the value of a data member in an array of classes without using a for loop?
Example:
If I have->
CObject Object[10]
Instead of looping through the array can I use something like memset to set the value of Object.Data in all ten elements?
Yes, in theory you could use memset. However, since memset only takes a char as the value to set the memory to, in practice this is normally only useful for initializing everything in your objects to zero.
Well, you could set the value in the constructer of CObject:
CObject::CObject()
{
member_variable = 5;
}
and when the array is initialized, member_variable for each CObject[] is set to 5.
this has its limitations though.
CObject::CObject()
{
member_variable = 5;
}
and when the array is initialized, member_variable for each CObject[] is set to 5.
this has its limitations though.
Quote:Original post by Plasmadog
Yes, in theory you could use memset. However, since memset only takes a char as the value to set the memory to, in practice this is normally only useful for initializing everything in your objects to zero.
This is still a very bad idea. The data layout of classes/structures in memory is not yours to control. In particular, if the class uses any kind of polymorphism, this would nuke the vtables.
Anyway, yes. You should be relying on the default constructor to specify default contents of objects.
I wouldn't, especially if it breaks the default construction of other instances. And you can't, alas, explicitly specify constructor parameters for an array's elements. Looping through is the best option. IIRC, placement new may offer some [hacky] joy.
Quote:Original post by geekalert
Well, you could set the value in the constructer of CObject:
CObject::CObject()
{
member_variable = 5;
}
and when the array is initialized, member_variable for each CObject[] is set to 5.
this has its limitations though.
Use this instead:
CObject::CObject() : member_variable(5){}
This way the variable will be created when the object is created, not set afterwards...
Another tip is to use std::vector, then you can use a number of stl-algorithms on it, such as "fill" in your case.
/.tnan
You have to iterate it in some way to set individual fields. The compiler will not be able to generate code without knowing what the field is and where it is in memory. A memset just blasts a chunk of memory with a single value and it will destroy your objects.
Quote:Original post by CJH
I wouldn't, especially if it breaks the default construction of other instances.
I would say that if "default construction" would more conveniently mean different things in different places, then you may want to rethink the design of the object entirely... :s
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement