473,799 Members | 3,866 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory allocation related question

Why is memory safe that function allocate inner object and return its
result? That inner object is destroyed when function come to the
"return" statement. Is default copy contructor doing some job? Can
somebody explain me what exactly is happening in the following code when
it invoke boo myres=calculate Something(12);

#include <iostream>
#include <cstdlib>
#include <math.h>

using namespace std;

class boo {
public:
int intValue;
double doubleValue;
};

boo calculateSometh ing(int arg) {
boo result;
result.intValue =arg;
result.doubleVa lue=arg*sqrt(ar g);
return result;
}
int main(int argc, char *argv[])
{
cout << "Hello, world!" << endl;
boo myres=calculate Something(12);
cout << myres.intValue << endl;
cout << myres.doubleVal ue << endl;
return EXIT_SUCCESS;
}

--
Mladen Adamovic
http://home.blic.net/adamm
http://www.shortopedia.com
http://www.froola.com
Feb 28 '06 #1
1 1837
Mladen Adamovic wrote:
Why is memory safe that function allocate inner object and return its
result?
In your example below, the object is returned by value. A _temporary_
object is created [somewhere] and used when function returns.
That inner object is destroyed when function come to the
"return" statement.
Yes.
Is default copy contructor doing some job?
Yes. The default one or the one that you declare/define.
Can
somebody explain me what exactly is happening in the following code when
it invoke boo myres=calculate Something(12);
What book on C++ are you reading that doesn't explain copy-construction
upon returning from a function?
#include <iostream>
#include <cstdlib>
#include <math.h>

using namespace std;

class boo {
public:
int intValue;
double doubleValue;
};

boo calculateSometh ing(int arg) {
boo result;
result.intValue =arg;
result.doubleVa lue=arg*sqrt(ar g);
return result;
}
int main(int argc, char *argv[])
{
cout << "Hello, world!" << endl;
boo myres=calculate Something(12);
(a) Memory for 'myres' is allocated.
(b) 'calculateSomet hing(12)' is called.
(c) Return value from 'calculateSomet hing' is a temporary object
(d) A temporary 'boo' object is constructed from the returned temporary
(d.1) The temporary returned from 'calculateSomet hing' is destroyed
(e) 'myres' is copy-initialised from a temporary constructed in (d)
(e.1) The temporary used to construct 'myres' is destroyed

The compiler is allowed to optimize away step (d) and construct 'myres'
as if the declaration statement were written:

boo myres(calculate Something(12));

Moreover, the compiler is allowed to forgo creation of a temporary when
'calculateSomet hing' is returning and construct the return value in the
'myres' object _directly_.
cout << myres.intValue << endl;
cout << myres.doubleVal ue << endl;
return EXIT_SUCCESS;
}


V
--
Please remove capital As from my address when replying by mail
Feb 28 '06 #2

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

Similar topics

2
1764
by: Lee Garrington | last post by:
Hey there, Is there a function that returns the amount of RAM free for memory allocation? Is there a function that will return the amount of memory your program currently uses through memory allocation? If not, is there any simple way of calculating this? Thx in advance
5
1696
by: Lionel | last post by:
Hi all, Just wondering exactly how memory is allocated using the new operator? More specifically I am interested in how the memory is calculated for globable variables? I recently stumbled into a problem which corrected my way of thinking. Now, people probably won't be able to answer much to that question, so I will give an example. This is example uses the qt library qstring.h, but I assume this would be similar to the C++ string.h...
16
2523
by: Jacob | last post by:
It is common practice (I've heard) to always catch allocation exceptions from "new". How is done in practice? What would be a common procedure (path of sequence) after such an event has occured? (For a multi-million LOC, GUI based application). It is also a common advice not to allocate objects with "new" unless absolutely required. The alternative is to keep objects on the stack, automatically allocated and deallocated by scope...
6
2702
by: Fred Zwarts | last post by:
Hello, I am trying to debug some complex debug code. In order to track the use of dynamically allocated memory, I replaced the standard global new and delete operators. (Not for changing the memory allocation algorithm, but for gathering some statistics and to find memory leaks.) This seems to work. However, I noticed that my replacing delete operator is not called
3
3760
by: Florin | last post by:
Hi all, I have a problem related to memory grow on a server application which is basically stateless (I have some static info loaded). The client accesses this server using remoting and it has worked for about 2 years without problems. The problem I have encountered lately is that the memory on server side started to grow and not to be released. I have checked first new functionalities but after isolating these on separate server, the...
62
17864
by: ivan.leben | last post by:
How can I really delete a preloaded image from memory/disk cache? Let's say I preload an image by creating an Image object and setting its src attribute to desired URL: var img = new Image(); img.src = ; Then I use the image a few more times by adding it into an Array object:
7
4695
by: toton | last post by:
Hi, I have a STL vector of of characters and the character class has a Boost array of points. The things are vector<Characterchars; and class Character{ private: array<Point,Npoints; }; Now are the memory layout is contiguous? i.e all the character resides side by side just like array, and all Points side by side insede the
17
9151
by: dtschoepe | last post by:
Hi, I have a homework project I am working on, so be forwarned, I'm new to C programming. But anyway, having some trouble with a memory allocation issue related to a char * that is a variable inside of a structure. I keep getting segmentation fault errors and I am having trouble understanding why. Here's the parts of the code in question... This is part of the .h file where the struct us defined...
9
2519
by: weidongtom | last post by:
Hi, I've written the code that follows, and I use the function add_word(), it seems to work fine *before* increase_arrays() is called that uses realloc() to allocate more memory to words. But *after* calling increase_arrays(), I received segmentation fault. I tried to step it through gdb, and I found out that after calling increase_arrays(), words's original value is modified, and if I tried to access it, I get <address 0x11 out of...
31
2725
by: Markus Pitha | last post by:
Hello, I'm using a template to simulate a LinkedList from Java.It works without problems, but when I want to use strings in main.cpp instead of char*, I get the following error message: $ ./Main terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct NULL not valid
0
9543
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
10488
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10257
jinu1996
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...
0
10029
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
9077
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...
0
5467
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
5588
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4144
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
3
2941
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.