This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

std::string::reserve vs std::vector::reserve


Hi,

I do not have the Standard, but the "C++ Programming Language" by BS states 
that both string reserve and operator= behave 'like' vector's. Well, in GCC 
2.95, 3.2, 3.3,3.4 and 4.0, it doesn't (so I'm probably wrong...).

A vector keeps its reserved capacity after an assignment, a string doesn't. 

I know this is because of the COW implementation. In fact, the string gets the 
capacity of the original... How does the Standard define the correct 
behaviour ? Will one day vector behave likewise ?

A Test program is in attachment.

Peter Soetens
-- 
K.U.Leuven, Mechanical Engineering, Robotics Research Group
<http://www.orocos.org> Tel: +32 16 322772
#include <string>
#include <vector>
#include <iostream>
using namespace std;

int main() {
    
    string a(10, 'a');
    string b(20, 'b');
    a.reserve( 100 );
    b.reserve( 200 );

    a = b; // changes contents, capacity() and size()

    cout << a.size() <<endl;
    cout << a.capacity() <<endl;


    vector<double> v(10, 0.1);
    vector<double> v2(20, 0.2);
    v.reserve(100 );
    v2.reserve(200 );

    v = v2; // changes only contents, size(), not capacity()

    cout << v.size() <<endl;
    cout << v.capacity() <<endl;
    
    return 0;
}

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]