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

Home Posts Topics Members FAQ

Return object question

Hi,

I have a question about returning an object in a function and calling a
copy constructor. As far as I understand, in the following code the copy
constructor may or may not be called, depending on the compiler:

A what()
{
A my_A;
// do something with A.
return A;
}

Suppose I have also a class B and a constructor for A from B:

A::A(const B& b);

The question is now about the following code:

A what()
{
B my_B;
// do something with B.
return B;
}

As far as I can see, the constructor 'A::A(const B& b)' must be called
in order to return an object A. But is it possible that after that
constructor some (stupid) compiler decides that the copy constructor for
A must be called also? Maybe some compiler might think that the copy
constructor must be called always if an object must be returned...

Thansk for any answers,

Jeroen
Apr 21 '07 #1
3 1695
On Sat, 21 Apr 2007 21:53:12 +0200 in comp.lang.c++, MathWizard
<no*****@please .comwrote,
>As far as I can see, the constructor 'A::A(const B& b)' must be called
in order to return an object A. But is it possible that after that
constructor some (stupid) compiler decides that the copy constructor for
A must be called also?
Yes, it is completely expected if your compiler is a little bit simple.
A compiler smart enough to skip it is doing "return value optimization".
The smart compiler is still required to check that the copy constructor
is accessible and give you an error if not, even though it's not called.

Apr 22 '07 #2
On Apr 21, 9:53 pm, MathWizard <no_m...@please .comwrote:
I have a question about returning an object in a function and calling a
copy constructor. As far as I understand, in the following code the copy
constructor may or may not be called, depending on the compiler:
A what()
{
A my_A;
// do something with A.
return A;
}
Correct. Technically, the semantics specified by the standard
require that the copy constructor be called, but the standard
then gives the compiler explicit authorization to merge my_A and
the return value, and not call the copy constructor. (Note that
while not calling the copy constructor is the most visible
effect, there are others as well.) This is called NRVO: Named
Return Value Optimization.
Suppose I have also a class B and a constructor for A from B:

A::A(const B& b);
The question is now about the following code:
A what()
{
B my_B;
// do something with B.
return B;
}
As far as I can see, the constructor 'A::A(const B& b)' must be called
in order to return an object A. But is it possible that after that
constructor some (stupid) compiler decides that the copy constructor for
A must be called also?
The formal semantics are almost the same as above: first you
construct a temporary of type A, then you copy it into the
return value. Again, the standard explicitly allows the
compiler to elide the copy.
Maybe some compiler might think that the copy
constructor must be called always if an object must be returned...
The copy constructor must be callable in both cases, or the code
is illegal. But I think that most compilers today elide the
copy in both cases.

--
James Kanze (Gabi Software) email: ja*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 22 '07 #3
James Kanze schreef:
On Apr 21, 9:53 pm, MathWizard <no_m...@please .comwrote:
>I have a question about returning an object in a function and calling a
copy constructor. As far as I understand, in the following code the copy
constructor may or may not be called, depending on the compiler:
>A what()
{
A my_A;
// do something with A.
return A;
}

Correct. Technically, the semantics specified by the standard
require that the copy constructor be called, but the standard
then gives the compiler explicit authorization to merge my_A and
the return value, and not call the copy constructor. (Note that
while not calling the copy constructor is the most visible
effect, there are others as well.) This is called NRVO: Named
Return Value Optimization.
>Suppose I have also a class B and a constructor for A from B:

A::A(const B& b);
>The question is now about the following code:
>A what()
{
B my_B;
// do something with B.
return B;
}
>As far as I can see, the constructor 'A::A(const B& b)' must be called
in order to return an object A. But is it possible that after that
constructor some (stupid) compiler decides that the copy constructor for
A must be called also?

The formal semantics are almost the same as above: first you
construct a temporary of type A, then you copy it into the
return value. Again, the standard explicitly allows the
compiler to elide the copy.
>Maybe some compiler might think that the copy
constructor must be called always if an object must be returned...

The copy constructor must be callable in both cases, or the code
is illegal. But I think that most compilers today elide the
copy in both cases.

--
James Kanze (Gabi Software) email: ja*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
OK, thanks for the answer James. But it looks like I'm stuck with my
'solution'. The thing is, I have a function which was originally
implemented as:

A special_functio n()
{
A my_A;
// do something with A.
return A;
}

I call it 'special_functi on' here, because here, if the copy constructor
is called, the copy constructor must do something different than in all
other cases when the copy constructor for 'A' is called.

So I wanted to make a solution with:

A special_functio n()
{
B my_B;
// do something with B.
return B;
}

so that I could force to use the constructor from B to A and thus
implement the slightly different behaviour for returning from
'special_functi on'. But if the copy constructor for A is then called
afterwards, then things will crash again...

I also thought of setting a property in class A, like:

A special_functio n()
{
A my_A;
// do something with A.

// Prepare for special behaviour of the copy constructor.
A.in_special_fu nction = true;

return A;
}

so that the copy constructor can test for that. But if NRVO is applied,
then the property remains set after A is returned and the special
behaviour of the copy constructor may be applied to the returned object
A somewhere in the code where I don't want it... For instance in the
situation:

void function2(A a)
{
}

function2(speci al_function());

Because the copy constructor is called when calling function2 while the
property 'A.in_special_f unction' may still be true at that time.

Any ideas maybe? Or is the description of my problem too vague :-)

Jeroen
Apr 23 '07 #4

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

Similar topics

20
2348
by: Jakob Bieling | last post by:
Hi! I am using VC++ 7.1 and have a question about return value optimization. Consider the following code: #include <list> #include <string> struct test {
5
3760
by: klaus triendl | last post by:
hi, recently i discovered a memory leak in our code; after some investigation i could reduce it to the following problem: return objects of functions are handled as temporary objects, hence their dtor is called immediately and not at the end of the function. to be able to use return objects (to avoid copying) i often assign them to a const reference. now, casting a const return object from a function to a non-const reference to this...
25
4149
by: cppaddict | last post by:
I'd like to know what goes on under the hood when methods return objects. Eg, I have a simple Point class with two members _x and _y. It's constructor, copy constructor, assignment operator and additon operator (which returns another Point object, and which my question is about) are as follows: Point::Point(int x, int y) : _x(x), _y(y) { }
14
2049
by: Gama Franco | last post by:
Hi, I'm designing an interface for a shared library, and I would like to know if there is a standard about how to return an object to the user. I will use exceptions to report errors, so there are at least four ways to do it. For example if we have a method named M, that receives a reference to parameter p and returns object o.
5
3048
by: Neal Coombes | last post by:
Posted to comp.lang.c++.moderated with little response. Hoping for better from the unmoderated groups: -------- Original Message -------- Subject: Return appropriately by value, (smart) pointer, or reference Date: 27 Aug 2005 15:13:23 -0400 From: Neal Coombes <nealc@trdlnk.com> Organization: Aioe.org NNTP Server To: (Usenet) Newsgroups: comp.lang.c++.moderated
5
1776
by: D. Shane Fowlkes | last post by:
This may be a very basic question but it's something I've never done before. I've looked at a couple of my favorite sites and books and can't find an answer either. I can write a Function to return a single value. No big deal. But I want to call a Function from another Sub and the function finds and returns an entire db record. Using ASP.NET (VB!), how can this be done and how can I differentiate between the fields/columns? For...
1
3479
by: Chris Roth | last post by:
I've been working with boost::threads to do some multithreading in my code and have run into some questions that I haven't been able to find answers to. I'll include some sample code to illustrate my questions. #include <boost/thread/thread.hpp> #include <iostream> using namespace std;
8
1793
by: sss.zhou | last post by:
Question about reference of the function return object. class A { public: std::string getString() const { return str_; } private:
18
2106
by: terminator(jam) | last post by:
consider: struct memory_pig{//a really large type: memory_pig(){ std::cout<<"mem pig default\n"; //etc... }; memory_pig(memory_pig const&){
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
10589
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
10340
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
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...
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
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4302
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 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.