HP C/aC++ for PA-RISC Software manual For -AA Standard Library, For a string type

Page 185

For -AA Standard Library

The following 4 defines can change the container initial allocation and growth ratio:

For an arbitrary container type:

#define _RWSTD_MINIMUM_NEW_CAPACITY size_t(32)

#define _RWSTD_NEW_CAPACITY_RATIO float(1.618)

For a string type:

#define _RWSTD_MINIMUM_STRING_CAPACITY size_t(128)

#define _RWSTD_STRING_CAPACITY_RATIO float(1.618)

For more precise control of containers, the following explicit specialization can be used.

The namespace scope functiontemplate __rw can be explicitly specialized to return the current size in elements of any container.

template <>

inline size_t __rw_new_capacity (size_t __size, const _Container*)

The parameters passed in are the current size in elements and the container's pointer. The default behavior results in an amortized constant time algorithm that dramatically increases rapidity while retaining a regard for space efficiency.

The defaults have been tuned with speed versus space optimization of container performance with regard to allocation of memory.

The ratio parameter must be above 1 for an amortized constant time algorithm. Lowering the ratio will lower rapidity and improve space efficiency. This effect will be most noticable when working with containers of few elements (less than 32).

The following is a container allocation example for both the -AP and -AA Standard library:

#include

namespace std {} using namespace std; #include

#include #define NUM 4

int printMallocInfo(const char*); #ifndef DEFAULT

//specialize default size

//Default buffer size for containers. #ifdef _HP_NAMESPACE_STD

namespace __rw { template <>

inline size_t __rw_new_capacity(size_t __size, const list*) { printf("......\n");

//if small grow by 5, else by 1/8 current size

return __size < 100 ? 5 : __size / 8;

}

}

#else // -AP template <>

inline size_t __rw_allocation_size(int*, size_t) { printf("......\n");

return sizeof(int) >= 1024 ? 1 : 5;

}

#endif // -AA #endif // DEFAULT int main() {

int count = 0;

list *tryit; for (int i = 0;ipush_back(i); printMallocInfo("1st entry added"); tryit->push_back(i + 1); printMallocInfo("2nd entry added"); count++;

}

printMallocInfo("at end");

Creating and Using Libraries 185

Image 185
Contents HP aC++/HP C A.06.28 Programmers Guide Page Contents +FP Contents Contents Contents Initialization and Termination Pragmas Pragma Directives and AttributesCopyright Notice and Identification Pragmas Data Alignment PragmasContents Preprocessing Directives 119 Standardizing Your Code 138 Using HP aC++ Templates 132Exception Handling 161 Optimizing HP aC++ Programs 156170 Tools and Libraries 175Mixing C++ with Other Languages 188 Strings 194 Arrays Files in Fortran Distributing Your C++ Products 195Migrating from HP C++ cfront to HP aC++ 198 Glossary 223 Index 227 Documentation feedback 221 Diagnostic Messages 222HP secure development lifecycle What’s in This Document About This DocumentIntended Audience This document uses the following conventions Typographical ConventionsRelated Documents Publishing HistoryHP-UX Release Name and Release Identifier HP-UX 11i ReleasesFollowing is a list of documents available with this release HP Encourages Your CommentsComponents of the Compilation System Getting Started with HP aC++C89 C99 ecom Ctcom Other HP aC++ executable files areCompiling a Simple Program Using the aCC CommandExecuting the Program Debugging ProgramsExamples of the aCC Command Compiler Command Syntax and Environmental VariablesAssembly Language Source Files .s Files Files on the aCC Command Line++ Source File .C file Preprocessed Source Files .i FilesEnvironment Variables Configuration Files .conf FilesObject Files .o Files Library Files .a and .so FilesACCMAXERR Environment Variable ACCFULLPATHNAMES Environment VariableCxxopts Environment Variable Cclibdir Environment VariableACC -L/mnt/proj/lib file.o ACC file.o Ccrootdir Environment VariableCxxmapfile Environment Variable Floating InstallationTmpdir Environment Variable Export CCROOTDIR=/mnt/CXX2.1HP aC++ Setting up Floating InstallationCommand-Line Options ACC -c sub.C prog.C Options to Control Code GenerationACC +DO11.22 +O3 app.C ILP32 Data Model and LP64 Data ModelCompiling in Networked Environments Using +DS to Specify Instruction SchedulingSize and Alignment of HP Compiler Data Types Data Alignment and StorageACC -S prog.C Fshort-enums Debugging Options+expandtypesindiag ACC +u1 app.CDifferences Between -g, -g0, and -g1 Options When to use -g, -g0, and -g1G1 Algorithm +macrodebug+pathtrace +noobjdebug+pathtrace=kind LocalNone Error Handling+pathtrace=globallocal ACC +p file.C+Wcontextlimit +wn+Wargs +We +wperfadvice+Weargs +WvExtensions to the Language Exception Handling+wsecurity +noeh+Onocxlimitedrange +OnofenvaccessFloating-Point Processing Options Fpevaldec FpevalNofpwidetypes +decfp+Onolibmerrno +FPmode+Oprefetchlatency +OnopreservedfpregsHeader File Options ACC -I include file.C Idirs -I- -Idirs +help Online Help Option+inlinelevel num Inlining OptionsDynamic Library OptionsExec LnameMinshared Linker Options+nostl +Onolibcalls=Usymbol Usymbol+Onodynopt +OnodynoptNative Language Support Option Options for Naming the Output File+ild +ildrelinkCode Optimizing Options Handling Null Pointers OptionsBasic Optimization Level Options ACC -z file.C+O1 +O0+O2 +O3+O4 Additional Optimization Options for Finer ControlACC +O3 prog.C +O4+Onofailsafe Ipo+nonrv +Onoaggressive Advanced +Ooptimization Options+Onolimit +Onoptrstoglobals=list+Onodatalayout +Onocrossregionaddressing+Onodataprefetch +Onofltacc+Onoinitcheck +Ofrequentlycalled+Ointegeroverflow +Onoinline+Olit +Onolooptransform +Olevel+Onoloopunroll +Onoopenmp+Onoparminit +opts+Onoparmsoverlap +Onoprocelim+Oshortdata +Orarelycalled+Onosignedpointers Profile-Based Optimization Options +Otypesafety+Onostoreordering +OunrollfactorInformation Embedding Options Parallel Processing OptionsDisplaying Optimization Information Annotate=structsRequired if -DPOSIXCSOURCEis used Option Matrix for -mt+tls=staticdynamic +Onoautopar+wlock Performance OptionsFast +Ofast+Onotlscallschangetp +Ofaster+nosrcpos +DSmodel+sb Porting Options+ub +uc+wdriver +w64bit+wendian This warning can be suppressed by adding an extra castRedirecting Output From This Option Preprocessor OptionsDname +Maked Maked+maked Examples+profilebucketsize Profiling Code OptionsUname +check Runtime Checking Options+check=all +check=noneCompiling with +check=boundspointer +check=boundsarray +check=boundspointerCheck off by any number out-of-bounds access Check off by one out-of-bounds access+check=lock +check=globals+check=malloc +check=thread +check=stackframevariablesnone+check=uninit +check=truncateexplicitimplicitCh = intval & 0xff +check=truncateexplicit +check=truncateimplicitAarm Standards Related OptionsAarm AC99 AC89Ag++ Agcc+legacyv5 AOa and -AOe+legacycpp +stl=rwnone +std=c89c99c++98c++11gccg++gnuWc,-ansiforscope,onoff +tru64Wc,-koeniglookup,onoff +tru64Tx,name Subprocesses of the CompilerMore Examples of -t Tx,nameWx,args Bdefault Symbol Binding OptionsBextern Passing Options to the Linker with -WBhiddendef BhiddenBprotected BprotecteddataTemplate Options +instincludesuffixes Trigraph Processing Suppression OptionVerbose Compile and Link Information Process Compiler 94/u 65/s 35/r 37/u 76/s 02/r ACC myfile.C -v -g1 ACC myfile.C -vg1 ACC -vg1 myfile.C Concatenating OptionsACC -V app.C Initialization and Termination Pragmas Pragma Directives and AttributesCopyright Notice and Identification Pragmas #pragma Versionid string Data Alignment Pragmas#pragma Versionid Software Product, Version 12345.A.01.05 #pragma align NData Alignment Pragmas Template Example Basic ExampleHandling Unaligned Data Implicit Access to Unaligned DataInteraction between pack and unalign pragmas is as follows #pragma unalign Typedef T1 T2Optlevel Pragma Optimization PragmasOptimize Pragma Floattrapson PragmaNoinline Pragma Other Pragmas Diagnostic PragmasBinding Pragma Defaultbinding PragmaEstimatedfrequency Pragma Extern PragmaHidden Pragma Hdrstop PragmaHpdefinedexternal Pragma Hpdefinedinternal PragmaPragma once POP PragmaProtected Pragma Ptrsstronglytyped PragmaStdc Cxlimitedrange Pragma #pragma Stdc FLOATCONSTDECIMAL64 on OFF DefaultStdc FLOATCONSTDECIMAL64 Pragma Stdc Fpcontract PragmaOMP Atomic Pragma Stdc Fenvaccess PragmaUnrollfactor Pragma OMP Critical Pragma OMP Barrier PragmaOMP for Pragma OMP Flush PragmaOMP Ordered Pragma OMP Master PragmaOMP Parallel Pragma OMP Parallel for PragmaOMP Sections Pragma OMP Parallel Sections PragmaOMP Single Pragma OMP Task PragmaOpenMP Clauses Copyprivate DefaultShared CopyinAttributes Attribute noreturn Attribute nonexposingAttribute nonexposing Attribute noreturnAttribute warnunusedresult Attribute formatAttribute visibility Overview of the Preprocessor Preprocessing DirectivesSyntax Usage GuidelinesSyntax Source File Inclusion #include, #includenextDescription Assertions #assert, #unassert#define mac very very long\ Replacement string Macro Replacement #define, #undefExamples Macros with ParametersConcatenating Tokens with the ## Operator Specifying String Literals with the # OperatorExample Following illustrates the ## operatorOther Macros Using Macros to Define ConstantsVar1 is #define Arraysize 1000float xARRAYSIZEUsing Constants and Inline Functions Instead of Macros Predefined Macros Assertions #assert, #unassertCode that compiles if the expression evaluates to zero Conditional Compilation #if, #ifdef, .. #endifHP aC++ predefines the following predicates Using the #if Directive Using the defined OperatorUsing the #ifdef and #ifndef Directives Using the #else Directive#line 5 myfile Line Control #lineExample Iostream Performance Improvement Pragma This macro enables the following non-standard featuresPragma Directive #pragma and Pragma Operator See page 96 for more information on pragmasTrigraph Sequences Error Directive #errorExamples Line below contains the trigraph sequence ??=??=line 5 myfile When this line is compiled it becomesInvoking Compile-Time Instantiation Using HP aC++ TemplatesScope and Precedence Template ProcessingUsage Explicit InstantiationPerformance Template class TablecharCompile-Time Instantiation Command-Line Option InstantiationFunction Template ACC -c +instcompiletime a.C ACC -c a.CPossible Duplicate Symbols in Shared Libraries Why Use Compile-Time InstantiationPossible Duplicate Symbols in Archive Libraries ScopeClass Templates ++ Template TutorialBuilding an Archive Library with +instauto/+instclose Building an Archive Library with Compile-time InstantiationFunction Templates HP aC++ Keywords Standardizing Your CodeBool Keyword HP aC++ KeywordsDynamiccast Keyword Compile time error message isAbove generates a compile-time error Explicit Keyword Classic example of this problem is an array class Mutable Keyword Connections Across Translation Units Namespace and using KeywordsUsing Nx // Where N is a namespace, x is a name in N Using- declarations and using- directivesAn Auxiliary Translation Unit IntPage Class Base Virtual void f Must have a virtual function to Volatile Keyword Typename Keyword Wchart KeywordTemplate Keyword Declare a class as a member of the class template C2 below Overloading new and delete for ArraysUse it as the name of the template C below Example Invalidargument RangeerrorStandard Exception Classes Following exceptions are thrown by the Standard C++ Library Exceptions Thrown by the Standard C++ LibraryTypeinfo Class Int before const typeinfo& const Unsupported FunctionalityMemfun1reft Memfunreft Iostream Optimizing HP aC++ Programs Setting Basic Optimization LevelsRequesting Optimization Level 1 OptimizationLevel 3 Optimization Additional Options for Finer ControlLevel 4 Optimization Enabling Aggressive OptimizationsProfile-Based Optimization Removing Compilation Time Limits When OptimizingEnabling Only Conservative Optimizations Limiting the Size of Optimized CodeCollecting Data for Profiling InstrumentationMaintaining Profile Data Files Sample.exe input.file1 Sample.exe input.file2Performing Profile-Based Optimization Pragmas That Control OptimizationACC -o sample.exe +Oprofile=use +O3 sample.C See Optimization Pragmas page 103 for more informationException Handling in C++ Exception HandlingFunction Try Block Examples Basic Exception Handling ExampleUsing Locks Using ThreadsDebugging Exception Handling Performance Considerations Rogue Wave Standard C++ LibraryRogue Wave Standard C++ Library Required Command-line OptionsRogue Wave Standard C++ Library 1.2.1 and Tools.h++ LpthreadThis option applies only to kernel threadsUsing -DHPACCTHREADSAFERBTREE Using -DTHREADSAFE with the cfront Compatible libstreamLimitations Cout endlACC -mt prog.c Pthreads Posix ThreadsException Handling OpenMP Implementation Parallel Programming Using OpenMPFunction Scoping OpenMP APIs are defined in the library libomp OpenMP Header FileOpenMP Library Environment Variables in OpenMP +Onoopenmp Command Line OptionOpenmp Macro Where, kind is either of of static, dynamic, or guidedExecution Environment Functions Runtime Library Functions in OpenMPExport OMPDYNAMIC=value Setenv Ompdynamic value Export OMPNESTED=value Setenv Ompnested valueOmpgetnumthreads OmpsetnumthreadsOmpgetmaxthreads OmpgetthreadnumOmpsetdynamic Lock FunctionsOmpgetdynamic OmpsetnestedOmpdestroylock and ompdestroynestlock Ompinitlock and ompinitnestlockOmpsetlock and ompsetnestlock Ompunsetlock and ompunsetnestlockOmptestlock and omptestnestlock Functions Timing FunctionsOmpgetwtime OmpgetwtickCreating and Using Libraries HP Specific Features of lex and yaccTools and Libraries Locale directive for lexHP aC++ Libraries Introduction to Using the Standard C++ LibraryStandard C++ Library IntroductionNon-Object-Oriented Design of the Standard C++ Library Differences between Standard C++ Library and Other LibrariesIncompatibilities Between the Library and the Standard Standard C++ Library ReferenceTools.h++ Library ACC -DHPACCUSINGMULTIPLIESINFUNCTIONAL test.cHP aC++ Runtime Support Library IOStream LibraryLinking to C++ Libraries Creating and Using Shared LibrariesLinking with Shared or Archive Libraries Specifying Other LibrariesExample of Creating and Using a Shared Library Using a Shared LibraryCreating a Shared Library Linking Archive or Shared LibrariesUpdating a Shared Library Advanced Shared Library FeaturesForcing the Export of Symbols in main Side Effects of C++ Shared Libraries Binding TimesRoutines and Options to Manage C++ Shared Libraries Linker Options to Manage Shared LibrariesAllocation Policies for Containers Standard HP-UX Libraries and Header FilesFor a string type For -AA Standard LibraryHP aC++ Executable Files HP aC++ File LocationsUsr/lib/hpux##/libCsup11.so ISO C++11 standard compliant HP aC++ Runtime Libraries and Header FilesUsr/lib/hpux##/libCsup.so Data Compatibility between C and C++ Mixing C++ with Other LanguagesCalling Other Languages HP aC++ Calling HP C Using the extern C Linkage SpecificationSyntax of extern C Examples of extern CExamples HP aC++ Calling HP C Differences in Argument Passing ConventionsMain Function Enter the nameJoann Joann has a balance HP C Calling HP aC++Running the Example Compiling and Running the Sample Programs To compile the example, run the following commandsCalling HP Fortran 90 from HP aC++ Using Reference Variables to Pass ArgumentsFunction Naming Conventions Example of Reference Variables as ArgumentsStrings Using extern C LinkageArrays Files in FortranApplications that use HP aC++ Shared Libraries Distributing Your C++ ProductsHP aC++ Files You May Distribute Installing your ApplicationLinking Your HP aC++ Libraries with Other Languages Terms for Distribution of HP aC++ Files General Guidelines for Migration Migrating from HP C++ cfront to HP aC++Getting Started with Migration CC +p cfrontfile.CNew Command-Line Options Command-Line DifferencesWriting Code for both Compilers Explicit Loading and Unloading of Shared LibrariesDescribes obsolete command-line options for HP aC++ Obsolete Command-Line OptionsPtv Changed Command-Line OptionsMigration Considerations when Using Exception Handling Migration Considerations when DebuggingException Handling is the Default See Debugging Options page 35 for complete informationMemory Allocation Failure and operator new Possible Differences when Exiting a Signal HandlerCalling unexpected Differences in setjmp/longjmp BehaviorThrowing an Object having an Ambiguous Base Class Unreachable catch ClausesStandards Based Libraries Migration Considerations when Using LibrariesFstream3C++ iostream and streambuf specialized to files HP C++ cfront Compatibility LibrariesManip3C++ iostream manipulators Man 3s filebufHP C++ cfront Complex Library Not Supported Migration Considerations Related to PreprocessingHP C++ cfront Task Library Not Supported Replace #include with complexObsolete Preprocessor Options Migration Considerations Related to StandardizationChanges in C++ Semantics Implicit Typing of Character String LiteralsExecution Order of Static Constructors in Shared Libraries Overload Resolution Ambiguity of Subscripting OperatorExplicit int Declaration Changes in C++ SyntaxMore Frequent Inlining of Inline Code Struct as Template Type Parameter is Permitted For Statement, New Scoping RulesEquivalent, valid HP aC++ code follows WC,-ansiforscope,onBase Template Class Reference Syntax Change This code compiles without error with HP aC++Tokens after #endif Overload not a KeywordDeclaring friend Classes Dangling Comma in enumStatic Member Definition Required Incorrect Syntax for Calls to operator new Using in Class DefinitionsDuplicate Formal Argument Names Ambiguous Function or Object DeclarationReference Initialization Overloaded Operations ++On HP aC++, the following error is generated Using operator new to Allocate ArraysCompiling this code HP aC++ generates the following error Parentheses in Static Member Initialization ListNon-constant Reference Initialization Qualified-id Required in Static Member Initialization ListVerbose Template Processing Information Migration Considerations when Using TemplatesDigraph White Space Separators CA aCfront Implicit Include Convention Converting Directed Mode to Explicit InstantiationCommon Template Migration Syntax Changes Documentation feedback Frequently Encountered Messages Diagnostic MessagesAC++ Message Catalog Aggressive GlossaryInternational Standard defines only synchronous exceptions See template Glossary Index SymbolsCrootdir FLOATTRAPSON, 103 FREQUENTLYCALLED, 106 HDRSTOP, 107 Hidden Index
Related manuals
Manual 15 pages 49.53 Kb