473,796 Members | 2,541 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

vector.push_bac k - pushes values or references?

Hi,

I'm a little new to stl so bear with me...Say I have the following
code:

vector<intvec;
int i = 3;
vec.push_back(i );
i=4;
cout<<vec.at(0) <<endl;

Looking at the signature of push_back, it seems to take a reference:

void push_back( const TYPE& val );

I wouldve thought that means the int i pass to the vector isn't
copied, but a reference to the original int is placed in the vector.
However, the above code returns 3, not 4, indicating the int has been
copied into the vector (on printing memory addresses, the ints are
stored in different memory addresses). My question is, why does the
push_back function take a reference, but yet still store a copy of the
object in the vector?

Cheers,

SR

Feb 17 '07 #1
6 21035
"Siam" <si*****@gmail. comwrote in message
news:11******** **************@ t69g2000cwt.goo glegroups.com.. .
Hi,

I'm a little new to stl so bear with me...Say I have the following
code:

vector<intvec;
int i = 3;
vec.push_back(i );
i=4;
cout<<vec.at(0) <<endl;

Looking at the signature of push_back, it seems to take a reference:

void push_back( const TYPE& val );

I wouldve thought that means the int i pass to the vector isn't
copied, but a reference to the original int is placed in the vector.
However, the above code returns 3, not 4, indicating the int has been
copied into the vector (on printing memory addresses, the ints are
stored in different memory addresses). My question is, why does the
push_back function take a reference, but yet still store a copy of the
object in the vector?

Cheers,

SR
..push_back() eventually uses the copy constructor of the object. So most
likly it accepts a reference, then calls the copy constructor on the
reference it has. Easy to determine this, just make a class with a private
copy constructor and try to make a vector out of it and use .push_back()
Feb 17 '07 #2
Siam wrote:
Hi,

I'm a little new to stl so bear with me...Say I have the following
code:

vector<intvec;
int i = 3;
vec.push_back(i );
i=4;
cout<<vec.at(0) <<endl;

Looking at the signature of push_back, it seems to take a reference:

void push_back( const TYPE& val );

I wouldve thought that means the int i pass to the vector isn't
copied, but a reference to the original int is placed in the vector.
However, the above code returns 3, not 4, indicating the int has been
copied into the vector (on printing memory addresses, the ints are
stored in different memory addresses). My question is, why does the
push_back function take a reference, but yet still store a copy of the
object in the vector?
Passing by reference insures only one copy of the object is made. If
the function used pass by value, the object would be copied twice.

--
Ian Collins.
Feb 17 '07 #3
Ian Collins wrote:
Siam wrote:
>>Hi,

I'm a little new to stl so bear with me...Say I have the following
code:

vector<intvec ;
int i = 3;
vec.push_back (i);
i=4;
cout<<vec.at( 0)<<endl;

Looking at the signature of push_back, it seems to take a reference:

void push_back( const TYPE& val );

I wouldve thought that means the int i pass to the vector isn't
copied, but a reference to the original int is placed in the vector.
However, the above code returns 3, not 4, indicating the int has been
copied into the vector (on printing memory addresses, the ints are
stored in different memory addresses). My question is, why does the
push_back function take a reference, but yet still store a copy of the
object in the vector?

Passing by reference insures only one copy of the object is made. If
the function used pass by value, the object would be copied twice.
Oops, s/insures/ensures/ :)

--
Ian Collins.
Feb 17 '07 #4
* Siam:
Hi,

I'm a little new to stl so bear with me...Say I have the following
code:

vector<intvec;
int i = 3;
vec.push_back(i );
i=4;
cout<<vec.at(0) <<endl;

Looking at the signature of push_back, it seems to take a reference:

void push_back( const TYPE& val );

I wouldve thought that means the int i pass to the vector isn't
copied, but a reference to the original int is placed in the vector.
However, the above code returns 3, not 4, indicating the int has been
copied into the vector (on printing memory addresses, the ints are
stored in different memory addresses). My question is, why does the
push_back function take a reference, but yet still store a copy of the
object in the vector?
Because std::vector can be used for any copyable type, and for some
types an object may have a lot of data to be copied, and/or copying the
object may involve dynamic allocation, which is (relatively) slow.

The reference passing means that an object that is expensive to copy is
only copied once, namely when copied into the vector's storage.

It's not copied in the process of being passed as argument, because with
a reference argument and a resonable compiler all that's passed (if
anything is passed!) is the object's memory address.

Using 'T const&' (or equivalently 'const T&') is a very common idiom for
objects that may be expensive to copy.

E.g., instead of writing a formal argument as 'std::string s', you
should as a matter of course write 'std::string const& s', even if
std::string might be expected to be heavily optimized and perhaps
directly supported by the compiler.

Caveat: don't do that for function results, e.g. don't declare a
function as 'std::string const& foo()' instead of 'std::string foo()'.

Because that might result in a dangling reference (the referred to
object doesn't exist after the function call has returned) and thus most
probably Undefined Behavior where undesirable things may happen.

Hope this helps,

- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 17 '07 #5
Ah great, thanks all :)

SR

Feb 17 '07 #6
Siam wrote:
>
void push_back( const TYPE& val );
Maybe, but that's not required by the language definition. These things
are specified in a different way. The requirement is that
vec.push_back(o bject) puts a copy of object into vec. Passing by value
is okay, as is passing by const reference.
I wouldve thought that means the int i pass to the vector isn't
copied, but a reference to the original int is placed in the vector.
However, the above code returns 3, not 4, indicating the int has been
copied into the vector (on printing memory addresses, the ints are
stored in different memory addresses). My question is, why does the
push_back function take a reference, but yet still store a copy of the
object in the vector?
The reason for storing by value is that that's what the specification
says. <gThe design of STL assumes that objects are cheap to create and
to copy, so STL algorithms and containers deal with values, not
references. If you need reference semantics, use TR1's reference_wrapp er
(also available from Boost), or use vector<TYPE*>. In both cases you
have to ensure that your objects hang around at least as long as the
container does. (For more details on reference_wrapp er, see chapter 8 of
my book, "The Standard C++ Library Extension"; for details on TR1's
shared_ptr, see chapter 2).

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Feb 17 '07 #7

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

Similar topics

15
9703
by: David Jones | last post by:
Hi I have a list of values stored in a vector e.g. std::vector<int> x; x = 1; x = 4; x = 2; x = 4;
6
1905
by: kittykat | last post by:
Hello, I am writing a program that will read each line of a file into a vector of vectors. This data will then be analysed. Here is what i have done: typedef vector<string> lines; ... vector<lines> SourceVector; string one_line;
6
3129
by: Matthias | last post by:
Hi, say I have a vector v1: std::vector<SomeType> v1; and I need a vector v2 of pointers to v1's elements: std::vector<SomeType*> v2;
5
2412
by: Billy Patton | last post by:
I have a polygon loaded into a vector. I need to remove redundant points. Here is an example line segment that shows redundant points a---------b--------c--------d Both b and c are not necessary. The function below is supposed to remove this It seems to work unitl the last point is removed. It seems to have something to do with the fact that vp->end() is a redundant point. THe test case is code so that "a" is the initial point,...
8
1704
by: imutate | last post by:
I have a std::vector with each element being a class, I push_back elements and then store values in the class object, later I look at these objects and the values are null. In essence: class celement { public: int x; ...
2
3303
by: ernesto | last post by:
Hi: I want to create my own vector class; I want to provide methods like: class Vector { public: void add(const Object* aVal); void remove(const Object* aVal); };
13
2092
by: arnuld | last post by:
this is the code: ------------------------------------------------------------------------- #include <iostream> #include <string> #include <vector> struct Pair { std::string name;
14
6460
by: meisterbartsch | last post by:
Hi, I want to assign predefined vallues to a vector, like: std::vector<doubletr; tr={3.36,2.09,1.47,1.1,0.87,0.72}; how do i do this? Am I able to assign values without using .push_back(); ?
10
2309
by: bejiz | last post by:
Hello, I would like to make a vector which can store vectors within. It is for finding the permutations of some numbers. I thought it would be easy to write some line of code to do this, but apparently, there is a problem for reading the vector within a vector. Here is my code. I have added some lines for printing words so that I could guess where the problem is: #include<iostream> #include<vector>
0
10459
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
10237
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...
1
10187
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10018
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
7553
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
6795
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();...
1
4120
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
2
3735
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
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.