473,770 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

efficiency of vector::push_ba ck?

Say I have objects of class C which are fairly large. Then consider:

vector<C> vc;
vc.push_back(C( ));

Naively this would seem to construct a temporary object C(), copy it
into the space owned by the vector, and then delete the temporary object.

I realize this is implementation dependent, but will most modern
compilers optimize away the creation of the temporary object, or is
there a compelling reason why this is not possible?

Thanks,
Mark
Jul 23 '05 #1
17 4172
Mark P wrote:
Say I have objects of class C which are fairly large. Then consider:

vector<C> vc;
vc.push_back(C( ));

Naively this would seem to construct a temporary object C(), copy it
into the space owned by the vector, and then delete the temporary object.

I realize this is implementation dependent, but will most modern
compilers optimize away the creation of the temporary object, or is
there a compelling reason why this is not possible?

Thanks,
Mark


I believe what happens is the:

1. vc is created with 0 capacity.
2. When push_back is called a temporary C object is constructed.
3. vc is then grown to capacity of 1.
4. As the vector is grown, another C object is constructed. This one is
inside of vc
5. Then the temporary C object (created by the call to push_back in 2) is
then copied (via the operator= or copy constructor into the C object that
is inside the vector (created in 4).
Jul 23 '05 #2
>Say I have objects of class C which are fairly
large. Then consider: vector<C> vc;
vc.push_back(C ()); Naively this would seem to construct a temporary
object C(), copy it into the space owned by the
vector, and then delete the temporary object. I realize this is implementation dependent, but
will most modern compilers optimize away the
creation of the temporary object, or is there a
compelling reason why this is not possible?


If constructing and copying objects of class C is
expensive, do not store them by value.
std::vector is usually implemented using a
dynamic array, so when it has to allocate memory,
it will copy its elements. Use pointers instead.

std::vector<C*> vc;
vc.push_back(ne w C);

--
Jonathan
[FAQ] - http://www.parashift.com/c++-faq-lite/

Jul 23 '05 #3
Mark P wrote:
Say I have objects of class C which are fairly large.
Then consider:

vector<C> vc;
vc.push_back(C( ));

Naively, this would seem to construct a temporary object C(),
copy it into the space owned by the vector
and then delete the temporary object.
Yes, but...
I realize [that] this is implementation dependent
but will most modern compilers optimize away
the creation of the temporary object
or is there a compelling reason why this is not possible? cat main.cc #include <iostream>
#include <vector>

class C {
private:
// representation
int I;
public:
// operators
friend
std::ostream& operator<<(std: :ostream& os, const C& c) {
return os << c.I;
}
// constructors
C(int i = 0): I(i) {
std::cerr << "C::C(int)" << std::endl;
}
C(const C& c): I(c.I) {
std::cerr << "C::C(const C&)" << std::endl;
}
~C(void) {
std::cerr << "C::~C(void )" << std::endl;
}
};

int main(int argc, char* argv[]) {
std::vector<C> vc;
vc.push_back(C( ));
return 0;
}
g++ -Wall -ansi -pedantic -O3 -o main main.cc
./main

C::C(int)
C::C(const C&)
C::~C(void)
C::~C(void)

Since the constructors, destructors and the push_back function
are all defined to be inline functions
the compiler can optimize away everything
except the diagnostic messages to standard error.
Jul 23 '05 #4
E. Robert Tisdale wrote:
Mark P wrote:
Say I have objects of class C which are fairly large.
Then consider:

vector<C> vc;
vc.push_back(C( ));

Naively, this would seem to construct a temporary object C(),
copy it into the space owned by the vector
and then delete the temporary object.

Yes, but...
I realize [that] this is implementation dependent
but will most modern compilers optimize away
the creation of the temporary object
or is there a compelling reason why this is not possible?


> cat main.cc

#include <iostream>
#include <vector>

class C {
private:
// representation
int I;
public:
// operators
friend
std::ostream& operator<<(std: :ostream& os, const C& c) {
return os << c.I;
}
// constructors
C(int i = 0): I(i) {
std::cerr << "C::C(int)" << std::endl;
}
C(const C& c): I(c.I) {
std::cerr << "C::C(const C&)" << std::endl;
}
~C(void) {
std::cerr << "C::~C(void )" << std::endl;
}
};

int main(int argc, char* argv[]) {
std::vector<C> vc;
vc.push_back(C( ));
return 0;
}
> g++ -Wall -ansi -pedantic -O3 -o main main.cc
> ./main

C::C(int)
C::C(const C&)
C::~C(void)
C::~C(void)

Since the constructors, destructors and the push_back function
are all defined to be inline functions
the compiler can optimize away everything
except the diagnostic messages to standard error.


I don't understand your conclusions here. It appears that the
temporaary is constructed and then copied rather than being constructed
"in place" within the vector. How do you know that everything but the
std error messages is optimized away?
Jul 23 '05 #5
> I realize this is implementation dependent, but will most modern compilers
optimize away the creation of the temporary object, or is there a
compelling reason why this is not possible?


Some compilers might have done that in the past. But it is now forbidden by
the standard (since there are situations where you rely on the exact number
of copy). The only copy they are allowed to optimize away is the return
value of a function. Ex: CObj obj = fun();
--
JS
Jul 23 '05 #6
In article <11************ *********@f14g2 000cwb.googlegr oups.com>,
Jonathan Mcdougall <jo************ ***@gmail.com> writes
If constructing and copying objects of class C is
expensive, do not store them by value.
std::vector is usually implemented using a
dynamic array, so when it has to allocate memory,
it will copy its elements. Use pointers instead.

std::vector<C* > vc;
vc.push_back(n ew C);


However if you store raw pointers you will have a memory leak if an
exception gets thrown across the point at which you define vc. Use a
suitable smart pointer instead.
--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/youcandoit/projects
Jul 23 '05 #7
In article <42************ *********@news. free.fr>, Jean-Sebastien Samson
<js***@yahoo.fr > writes
I realize this is implementation dependent, but will most modern compilers
optimize away the creation of the temporary object, or is there a
compelling reason why this is not possible?


Some compilers might have done that in the past. But it is now forbidden by
the standard (since there are situations where you rely on the exact number
of copy). The only copy they are allowed to optimize away is the return
value of a function. Ex: CObj obj = fun();


No. While there is rather more restriction on when a copy may be
optimised away it is nowhere near as strict as that.
--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/youcandoit/projects
Jul 23 '05 #8
On Fri, 13 May 2005 07:47:51 GMT, Mark P <no*@my.real.em ail> wrote:
E. Robert Tisdale wrote:
Mark P wrote:
Say I have objects of class C which are fairly large.
Then consider:

vector<C> vc;
vc.push_back(C( ));
<snip> Since the constructors, destructors and the push_back function
are all defined to be inline functions
the compiler can optimize away everything
except the diagnostic messages to standard error.


I don't understand your conclusions here. It appears that the
temporaary is constructed and then copied rather than being constructed
"in place" within the vector. How do you know that everything but the
std error messages is optimized away?


I always thought that the point of optimization was invisibility to
the user, other than perhaps execution time or program size. It would
be quite surprising to find that the result of a calculation varied
with turning on and off compiler optimization switches.

By requiring the program to print error messages logging the execution
path, the compiler cannot optimize away "everything ".
--

Best wishes,

Bob
Jul 23 '05 #9
In article <j0************ *************** *****@4ax.com>, Robert W Hand
<rw****@NOSPAMo peramail.com> writes

I always thought that the point of optimization was invisibility to
the user, other than perhaps execution time or program size. It would
be quite surprising to find that the result of a calculation varied
with turning on and off compiler optimization switches.

By requiring the program to print error messages logging the execution
path, the compiler cannot optimize away "everything ".

But C++ gives specific authorisation wrt copy ctors. Under that licence
side effects of a copy ctor are not required to happen (and may also
happen at semi-arbitrary points if the compiler determines that it
wishes to create a temporary copy)

--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/youcandoit/projects
Jul 23 '05 #10

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

Similar topics

4
9803
by: Hitesh Bhatiya | last post by:
Hi all, I have written a small program to accept some socket connections, which are then added to a vector (using push_back). But after a few calls to the push_back function, it deleted the object that was added last. Could someone please tell me why this happens ? Am I doing something wrong here ?
30
4501
by: Antonios Christofides | last post by:
Hi, As I read in the archives, the performance problem caused by memory reallocations during vector::push_back is a common one. My first C++ program is suffering from it: 300 thousand push_backs result, according to the profiler, in 20 reallocations; these 20 reallocations account for 3.6 seconds (Celeron 1.3G), which is 40% of total execution time. What I don't understand: why is the reallocation code so complex? I
4
1578
by: whocares | last post by:
hi everyone. i'm currently experiencing a strange problem under vc++ 2005 express. i hope someone has a hint for me, i'm kind of lost atm. i'm using a vectors of pointers in my code. using the release build i can add and remove elements aslong as i stay below a certain vector size (13 in this case, no joke). as soon as the vector tries to add element 14 i get a runtime error.
3
3225
by: Al | last post by:
What is the problem with this code? It always crashes at the 'push_back'. I found that thanks to debugging. Any Ideas? Other question: what is a faster way to convert a string to an integer? Is there a built-in function to do that? Here's the code: #include <iostream> #include <fstream> #include <vector> #include <string>
6
21032
by: Siam | last post by:
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;
6
11616
by: jmsanchezdiaz | last post by:
CPP question: if i had a struct like "struct str { int a; int b };" and a vector "std::vector < str test;" and wanted to push_back a struct, would i have to define the struct, fill it, and then push_back it, or could i pushback the two ints directly somehow? Thanks for all.
0
9617
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
9453
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
10254
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
10099
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
8929
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
5354
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
5481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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
2849
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.