The C++ get_allocator() program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: To return a copy of the allocator object used to construct the string using get_allocator() in C++ programming

To show: How to use get_allocator() function to return a copy of the allocator object used to construct the string in C++ programming

 

// the C++ get_allocator() program example

#include <string>

#include <iostream>

using namespace std;

 

int main(void)

{

// using the default allocator

string str1 = "1234";

basic_string <char> str2 = "567ABC";

basic_string <char, char_traits<char>, allocator<char> > str3 = "DefauLt";

cout<<"str1 = "<<str1<<endl;

cout<<"str2 = "<<str2<<endl;

cout<<"str3 = "<<str3<<endl;

 

// str4 will use the same allocator class as str1

basic_string <char> str4(str1.get_allocator());

basic_string <char>::allocator_type xchar = str1.get_allocator();

str4 = "Just a string";

cout<<"str4 = "<<str4<<endl;

 

if (xchar == str1.get_allocator())

cout<<"The allocator objects xchar and str1.get_allocator() are equal."<<endl;

else

cout<<"The allocator objects xchar and str1.get_allocator() are not equal."<<endl;

 

// you can now call functions on the allocator class xchar used by str1

string str5(xchar);

return 0;

}

 

Output example:

 

str1 = 1234

str2 = 567ABC

str3 = DefauLt

str4 = Just a string

The allocator objects xchar and str1.get_allocator() are equal.

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index