473,549 Members | 2,708 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning const references to class data

Hello,

I'm wondering if returning const references to a class member is
generally faster than returning a copy of the object.
Consider this code:

class A
{
std::string data;
public:
const std::string& get_data() const { return data; }
}

versus

class B
{
std::string data;
public:
std::string get_data() const { return data; }
}

If I now have this code:

// ...
A a;
B b;

std::string str = a.get_data();
std:.string str = b.get_data();

Which assignment will be faster? My first impression was, that since (I
guess) data is not copied in A::get_data but returned by reference, we
save one call of a copy constructor. But is this also the case in
"reality"? Which version would you prefer?

Thanks,
Matthias
Jul 22 '05 #1
2 1671

matthias_k wrote:
Hello,

I'm wondering if returning const references to a class member is
generally faster than returning a copy of the object.
Consider this code:

class A
{
std::string data;
public:
const std::string& get_data() const { return data; }
}

versus

class B
{
std::string data;
public:
std::string get_data() const { return data; }
}

If I now have this code:

// ...
A a;
B b;

std::string str = a.get_data();
std:.string str = b.get_data();

Which assignment will be faster? My first impression was, that since (I guess) data is not copied in A::get_data but returned by reference, we save one call of a copy constructor. But is this also the case in
"reality"? Which version would you prefer?

Thanks,
Matthias


For built-in types (or small user-defined types), class B will probably
be faster, although if inlining is performed, they might probably be
the same.

For expensive user-defined types (e.g., require allocation etc), class
A will probably be faster, although if inlining (and heavy
optimisation) is performed, they might probably be the same. But
usually for these types, its best to return by const reference.

-shez-

Jul 22 '05 #2
shez wrote:
matthias_k wrote:
Hello,

I'm wondering if returning const references to a class member is
generally faster than returning a copy of the object.
Consider this code:

class A
{
std::string data;
public:
const std::string& get_data() const { return data; }
}

versus

class B
{
std::string data;
public:
std::string get_data() const { return data; }
}

If I now have this code:

// ...
A a;
B b;

std::string str = a.get_data();
std:.string str = b.get_data();

Which assignment will be faster? My first impression was, that since


(I
guess) data is not copied in A::get_data but returned by reference,


we
save one call of a copy constructor. But is this also the case in
"reality"? Which version would you prefer?

Thanks,
Matthias

For built-in types (or small user-defined types), class B will probably
be faster, although if inlining is performed, they might probably be
the same.

For expensive user-defined types (e.g., require allocation etc), class
A will probably be faster, although if inlining (and heavy
optimisation) is performed, they might probably be the same. But
usually for these types, its best to return by const reference.

-shez-


Yes, I should have clarified that I was only concerned about complex
types. But basically that's what I thought as well, thanks shez.

Regards,
Matthias
Jul 22 '05 #3

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

Similar topics

7
20337
by: Pablo J Royo | last post by:
Hello: i have a function that reads a file as an argument and returns a reference to an object that contains some information obtained from the file: FData &ReadFile(string FilePath); But , for example, when the file doesnt exists, i should not return any reference to a bad constructed object, so i need something as a NULL reference...
4
1761
by: Patrick | last post by:
I want to achieve the following behaviour but I am having trouble getting there...bare with me im knew to c++ , so its probably rather trivial! To have a class ClassA, and composed within this class is an instance of another class, ClassB. I want to have a method getClassB that returns a reference to the instance of ClassB composed within...
18
2119
by: cppaddict | last post by:
Hi, Is it considered bad form to have the subscript operator return a const reference variable? If not, what is the proper way to do it? My question was prompted by the code below, my problematic attempt to implement a subscript operator that returns a const reference. The dubious code is marked at the end. <code>
12
3262
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global function { MFVec res = z1; res += z2 return res; // WHY???
19
1925
by: Steven T. Hatton | last post by:
I believe it is technically possible to return a pointer to the first element of an array. I can persuade the returned pointer to act like an array, with some qualifications. I'm specifically interested in multidimensional arrays. It is often said that arrays and pointers are virtually identical. My observations are that my (gcc)...
10
10270
by: Fraser Ross | last post by:
I need to know the syntax for writing a reference of an array. I haven't seen it done often. I have a class with a member array and I want a member function to return an reference to it. Returning a pointer to the first element might do but I want to do what I've said. Fraser.
17
3219
by: djcredo | last post by:
Hey all, I want to return a pointer to a struct. Here is what I'lm trying to do: struct Position{ int x; int y; }; Position* GraphicTag::getRenderCentre(){
3
2792
by: Belebele | last post by:
I have an Element class which is abstract and I would like to have an object of the Iterator class to iterate over a range of elements. I would like to use std::for_each to instrument the iteration, which forces me to have certain interface on the Iterator class. struct Element { virtual ~Element() = 0; };
23
2906
by: pauldepstein | last post by:
Below is posted from a link for Stanford students in computer science. QUOTE BEGINS HERE Because of the risk of misuse, some experts recommend never returning a reference from a function or method. QUOTE ENDS HERE I have never heard anyone else say that it is a problem for a function
0
7451
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...
0
7720
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. ...
0
7960
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...
1
7475
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7812
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...
1
5372
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...
0
5089
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...
0
3501
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...
0
3483
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.