473,804 Members | 3,247 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Object Initialization


Consider a simple POD:
struct Blah
{
int a;

const char* p_b;

unsigned c;

double d;
};
Now, let's say we want to create a "zero-initialized" object of this class,
yielding:

a == 0
p_b == null pointer value (not necessarily all bits zero)
c = 0U
d = 0.0
The only way to achieve this is via:

Blah poo = Blah();
....which ridiculously, ludacrisly, may create a temporary if it wishes.
Okay... so let's say we have a template. This template is a function:
template<class T> void Monkey();
What this function does is define an automatic local object of type T and
makes it zero initialized.
template<class T> void Monkey()
{
T poo = T();
}
But... this template function is to be designed to work with ALL types
(intrinsics, POD's, non-POD's, what have you). But then some-one goes and
does:

Monkey<std::ost ringstream>();

which brings in the bullshit complication of not being able to copy certain
types (ie. the above syntax must have the choice to copy).

Anyway, short of using dynamic memory allocation, I've found one way of
making a zero-initialized automatic object. . . but it has to be const:
template<class T> void Monkey()
{
T const &poo = T();
}
Now Monkey<std::ost ringstream> will work, and the "temporary" bound to the
reference lasts for the length of the function... but it has to be const.

Okay anyway... can anyone think of a way of doing this to achieve a *non-
const* object? So far all I've got is:

template<class T> void Monkey()
{
T &poo = *new T();
delete &poo;
}
....and all of this because of the "function declaration Vs object
definition" bullshit! If only the "extern" keyword were mandatory... or if
the "class" keyword could specify that it's an object definition...
While I'm on the subject... is there actually anything "wrong" with using
dynamic memory allocation? I myself don't know assembly language, so I can't
see what's going on under the hood... but could you tell me, do the
following two programs result in the same assembly code?

Program 1:

int main()
{
int k = 5;

k -= 2;
}
Program 2:

int main()
{
int &k = *new int(5);

k -=2;

delete &k;
}
Is there anything inherently "efficent" or "...bad" about using dynamic
memory allocation... ?
-JKop
Jul 22 '05 #1
4 2499
Is there anything inherently "efficent" or "...bad" about using dynamic
memory allocation... ?


TYPO

"inefficent "
-JKop
Jul 22 '05 #2
JKop wrote:

Is there anything inherently "efficent" or "...bad" about using dynamic
memory allocation... ?

Well, it's probably a bit less efficient for small objects than using
the automatic storage, but of course, that won't meet your requirements.

Jul 22 '05 #3
JKop wrote:
Is there anything inherently "efficent" or "...bad" about using dynamic
memory allocation... ?


Putting objects on the "stack" (automatic storage) is more typically
efficient since all of the work needed to allocate and deallocate memory
for the object can be done during compile time. The downside is that
there is no standard way to see if you running out of stack space.

With dynamically allocated memory (free store) work needs to be done
during runtime, which means slower code. Depending on the compiler,
run-time library and platform the performance difference can be quite
significant. With dynamic memory allocation there is also the risk of
heap fragmentation. This is a concern when a system has to run 24/7 and
frequently allocates and deallocates memory. This can fragment the heap
in such away that there is no free memory block large enough to fulfill
an allocation request even though the total amount of free memory is
sufficient. Another disadvantage of dynamically allocated objects is
that you have to explicitly deallocate too, unless you use smart
pointers. Without smart pointers it is very hard to write exception safe
leak free code.

--
Peter van Merkerk
peter.van.merke rk(at)dse.nl
Jul 22 '05 #4

I'm curious: if you want to initialize everything (to zero, or anything
else, for that matter), why not just have a constructor that does it for
you? That's what they're for, after all. In my opinion, having all the
members of a class be set to zero initially is no different conceptually
from having them set to any other desired value. Granted, member pointers
are a different matter, since you generally don't want them to be non-zero
unless they're valid, but still, the constructor can simply set those to
NULL, if needed. But in any case, adding a default constructor that
initializes everything to whatever you want them to be seems easier than
messing around with templates like that. And if one day, you decide that
you want one of those members to initialize to something other than zero,
all you have to do is change the single assignment (or better, the single
entry in your initializer list).

-Howard

Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

106
5620
by: A | last post by:
Hi, I have always been taught to use an inialization list for initialising data members of a class. I realize that initialsizing primitives and pointers use an inialization list is exactly the same as an assignment, but for class types it has a different effect - it calls the copy constructor. My question is when to not use an initalisation list for initialising data members of a class?
8
1798
by: nrhayyal | last post by:
hi all, is it a good idea to assign object to pointers without initialising it to NULL? suppose if i have a class TEST class ELEMENT { private: int a; string s1;
8
1841
by: Mark Neilson | last post by:
1. What is the best way to make a single instance of my top level class (DLL) internally available to all other members of the assembly? The top level object is where all other access is made in to the program. Where and how do I declare and initialise this object? For instance, it would have property implementation like this: //******************************************* public MyClass1 Class1 {
7
1671
by: xllx.relient.xllx | last post by:
Q1: What happens when you apply parenthesis to the class type name? Is the constructor for the class called and returns an object?, or what? in main...: MyClass(); // end
4
1562
by: sks | last post by:
hi , i Have a code snippet as follows class ABC { int &r; ABC(int a=0): r(a) {} }; int main() {
13
2075
by: Frederick Gotham | last post by:
I have just been reading 8.5 in the Standard, and am trying to make sense of the different kinds of initialisations. Up until now, I thought of an object as either NOT being initialised (i.e. containing garbage), or being default initialised (i.e. containing the default value for that type). Here are some examples of the former: struct MyStruct {
8
399
by: sarathy | last post by:
Hi, I read the following points in K&R "Section A8.7 Initialization". Seems like i have a problem with them. * All expressions in the initialization of constant object/array must be constant expression. * Expressions in the initializer for an auto or register object or array must likewise be constant expressions if the initializer is a brace enclosed list.
4
3717
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and value-initialization. I think default-init calls default constructor for class objects and sets garbage values to PODs. Value-init also calls default constructor for class objects and sets 0s to POD types. This is what I've learned from the books (especially...
13
2343
by: WaterWalk | last post by:
Hello. When I consult the ISO C++ standard, I notice that in paragraph 3.6.2.1, the standard states: "Objects with static storage duration shall be zero-initialized before any other initialization takes place." Does this mean all non-local objects will be zero-initialized before they are initialized by their initializers(if they have)? For example: int g_var = 3; int main() {}
5
399
by: kiryazev | last post by:
Hello. Given the code below does C++ Standard guarantee that the function my_init() will be called before main()? struct A { A() { my_init(); } };
0
9708
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9588
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,...
0
10085
tracyyun
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...
0
9161
agi2029
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...
1
7625
isladogs
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...
0
6857
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();...
0
5527
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...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2999
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.