HP C/aC++ for PA-RISC Software manual Standard C++ Library Reference

Page 178

Smaller Source Code

There are approximately 50 different algorithms and about a dozen major data structures. This separation reduces the source code size, and decreases the risk of similar activities with dissimilar interfaces. In the absense of this separation, each algorithm must be implemented in each data structure. This requires additional member functions apart from those in the present scheme.

Flexibility

The algorithms that are separated from data structures can be used with conventional C++ pointers and arrays. Algorithms encapsulated within a class hierarchy do not have this ability because C++ arrays are not objects.

Efficiency

The STL in particular, and the Standard C++ Library in general, provide a low-level approach to develop C++ applications. This low-level approach is useful when specific programs require an emphasis on efficient coding and execution speed.

Iterators: Mismatches and Invalidations

The Standard C++ Library data structures use pointer-like objects called iterators to describe the contents of a container. Given the architecture of the library architecture, it is impossible to verify whether the iterator elements are matched or derived from the same container. Using a beginning iterator from one container with an ending iterator from another produces unexpected results. It is very important to know that iterators are invalidated as a result of a subsequent insertion or deletion from the underlying container class. The use of an invalid iterator produces unexpected results.

Familiarity with the Standard C++ Library reduces the number of errors related to iterators.

Templates: Errors and Code Bloat

The flexibility and power of templatized algorithms is, with most compilers, results in a loss of precision in diagnostics. Errors in the parameter lists of generic algorithms is sometimes displayed only as obscure compiler errors for internal functions. These errors are defined many levels deep in template expansions. Familiarity with algorithms and their requirements is necessary to use the standard library. Heavy reliance on templates causes programs to grow larger than expected. You can minimize this problem by recognizing the cost of instantiating a particular template class, and by making appropriate design decisions. As compilers become more fluent in templates, the problem of size is reduced.

Multithreading Problems

When you use the Standard C++ Library in a multithreaded environment, the iterators cannot safely pass between threads. This is because iterators are independent of the containers they operate on. It is impossible to protect a container when it spawns iterators in multiple threads as iterators are used to modify a non-const container. Use thread-safe wrappers, such as those provided by Tools.h++ Library to access a container from multiple threads.

Standard C++ Library Reference

The Standard C++ Library Reference provides an alphabetical listing of all of the classes, algorithms, and function objects in the prior Rogue Wave implementation of the Standard C++ Library.

Incompatibilities Between the Library and the Standard

The ANSI/ISO C++ International Standard is different from Standard C++ Library. For example, the times function object in the functional header file. In the standard, times is renamed to multiplies.

To use multiplies in your code and to be compatible with the ANSI/ISO C++ International Standard, use a conditional compilation flag on the aCC command line.

Example:

178 Tools and Libraries

Image 178
Contents HP aC++/HP C A.06.28 Programmers Guide Page Contents +FP Contents Contents Contents Copyright Notice and Identification Pragmas Pragma Directives and AttributesInitialization and Termination Pragmas Data Alignment PragmasContents Preprocessing Directives 119 Using HP aC++ Templates 132 Standardizing Your Code 138Optimizing HP aC++ Programs 156 Exception Handling 161Tools and Libraries 175 170Mixing C++ with Other Languages 188 Migrating from HP C++ cfront to HP aC++ 198 Distributing Your C++ Products 195Strings 194 Arrays Files in Fortran Documentation feedback 221 Diagnostic Messages 222 Glossary 223 Index 227HP secure development lifecycle Intended Audience About This DocumentWhat’s in This Document Typographical Conventions This document uses the following conventionsHP-UX Release Name and Release Identifier Publishing HistoryRelated Documents HP-UX 11i ReleasesHP Encourages Your Comments Following is a list of documents available with this releaseC89 C99 ecom Ctcom Getting Started with HP aC++Components of the Compilation System Other HP aC++ executable files areExecuting the Program Using the aCC CommandCompiling a Simple Program Debugging ProgramsCompiler Command Syntax and Environmental Variables Examples of the aCC Command++ Source File .C file Files on the aCC Command LineAssembly Language Source Files .s Files Preprocessed Source Files .i FilesObject Files .o Files Configuration Files .conf FilesEnvironment Variables Library Files .a and .so FilesCxxopts Environment Variable ACCFULLPATHNAMES Environment VariableACCMAXERR Environment Variable Cclibdir Environment VariableCcrootdir Environment Variable ACC -L/mnt/proj/lib file.o ACC file.oTmpdir Environment Variable Floating InstallationCxxmapfile Environment Variable Export CCROOTDIR=/mnt/CXX2.1Setting up Floating Installation HP aC++Command-Line Options ACC +DO11.22 +O3 app.C Options to Control Code GenerationACC -c sub.C prog.C ILP32 Data Model and LP64 Data ModelUsing +DS to Specify Instruction Scheduling Compiling in Networked EnvironmentsACC -S prog.C Data Alignment and StorageSize and Alignment of HP Compiler Data Types +expandtypesindiag Debugging OptionsFshort-enums ACC +u1 app.CG1 Algorithm When to use -g, -g0, and -g1Differences Between -g, -g0, and -g1 Options +macrodebug+pathtrace=kind +noobjdebug+pathtrace Local+pathtrace=globallocal Error HandlingNone ACC +p file.C+Wargs +wn+Wcontextlimit +Weargs +wperfadvice+We +Wv+wsecurity Exception HandlingExtensions to the Language +noehFloating-Point Processing Options +Onofenvaccess+Onocxlimitedrange Nofpwidetypes FpevalFpevaldec +decfp+Oprefetchlatency +FPmode+Onolibmerrno +OnopreservedfpregsHeader File Options ACC -I include file.C Idirs -I- -Idirs Online Help Option +helpInlining Options +inlinelevel numExec Library OptionsDynamic Lname+nostl Linker OptionsMinshared +Onolibcalls=+Onodynopt UsymbolUsymbol +Onodynopt+ild Options for Naming the Output FileNative Language Support Option +ildrelinkBasic Optimization Level Options Handling Null Pointers OptionsCode Optimizing Options ACC -z file.C+O2 +O0+O1 +O3ACC +O3 prog.C Additional Optimization Options for Finer Control+O4 +O4+nonrv Ipo+Onofailsafe +Onolimit Advanced +Ooptimization Options+Onoaggressive +Onoptrstoglobals=list+Onodataprefetch +Onocrossregionaddressing+Onodatalayout +Onofltacc+Ofrequentlycalled +Onoinitcheck+Olit +Onoinline+Ointegeroverflow +Onoloopunroll +Olevel+Onolooptransform +Onoopenmp+Onoparmsoverlap +opts+Onoparminit +Onoprocelim+Onosignedpointers +Orarelycalled+Oshortdata +Onostoreordering +OtypesafetyProfile-Based Optimization Options +OunrollfactorDisplaying Optimization Information Parallel Processing OptionsInformation Embedding Options Annotate=structsOption Matrix for -mt Required if -DPOSIXCSOURCEis used+Onoautopar +tls=staticdynamicFast Performance Options+wlock +Ofast+nosrcpos +Ofaster+Onotlscallschangetp +DSmodel+ub Porting Options+sb +uc+wendian +w64bit+wdriver This warning can be suppressed by adding an extra castDname Preprocessor OptionsRedirecting Output From This Option +maked Maked+Maked ExamplesUname Profiling Code Options+profilebucketsize +check=all Runtime Checking Options+check +check=none+check=boundsarray +check=boundspointer Compiling with +check=boundspointerCheck off by one out-of-bounds access Check off by any number out-of-bounds access+check=globals +check=lock+check=malloc +check=stackframevariablesnone +check=threadCh = intval & 0xff +check=truncateexplicit +check=truncateexplicitimplicit+check=uninit +check=truncateimplicitAarm Standards Related OptionsAarm Ag++ AC89AC99 Agcc+legacycpp AOa and -AOe+legacyv5 +std=c89c99c++98c++11gccg++gnu +stl=rwnoneWc,-koeniglookup,onoff +tru64Wc,-ansiforscope,onoff +tru64More Examples of -t Subprocesses of the CompilerTx,name Tx,nameWx,args Bextern Symbol Binding OptionsBdefault Passing Options to the Linker with -WBprotected BhiddenBhiddendef BprotecteddataTemplate Options Trigraph Processing Suppression Option +instincludesuffixesVerbose Compile and Link Information Process Compiler 94/u 65/s 35/r 37/u 76/s 02/r ACC -V app.C Concatenating OptionsACC myfile.C -v -g1 ACC myfile.C -vg1 ACC -vg1 myfile.C Pragma Directives and Attributes Initialization and Termination PragmasCopyright Notice and Identification Pragmas #pragma Versionid Software Product, Version 12345.A.01.05 Data Alignment Pragmas#pragma Versionid string #pragma align NData Alignment Pragmas Basic Example Template ExampleImplicit Access to Unaligned Data Handling Unaligned Data#pragma unalign Typedef T1 T2 Interaction between pack and unalign pragmas is as followsOptimize Pragma Optimization PragmasOptlevel Pragma Floattrapson PragmaNoinline Pragma Diagnostic Pragmas Other PragmasEstimatedfrequency Pragma Defaultbinding PragmaBinding Pragma Extern PragmaHpdefinedexternal Pragma Hdrstop PragmaHidden Pragma Hpdefinedinternal PragmaProtected Pragma POP PragmaPragma once Ptrsstronglytyped PragmaStdc FLOATCONSTDECIMAL64 Pragma #pragma Stdc FLOATCONSTDECIMAL64 on OFF DefaultStdc Cxlimitedrange Pragma Stdc Fpcontract PragmaUnrollfactor Pragma Stdc Fenvaccess PragmaOMP Atomic Pragma OMP for Pragma OMP Barrier PragmaOMP Critical Pragma OMP Flush PragmaOMP Parallel Pragma OMP Master PragmaOMP Ordered Pragma OMP Parallel for PragmaOMP Single Pragma OMP Parallel Sections PragmaOMP Sections Pragma OMP Task PragmaOpenMP Clauses Shared DefaultCopyprivate CopyinAttributes Attribute nonexposing Attribute nonexposingAttribute noreturn Attribute noreturnAttribute visibility Attribute formatAttribute warnunusedresult Syntax Preprocessing DirectivesOverview of the Preprocessor Usage GuidelinesDescription Source File Inclusion #include, #includenextSyntax Assertions #assert, #unassertExamples Macro Replacement #define, #undef#define mac very very long\ Replacement string Macros with ParametersExample Specifying String Literals with the # OperatorConcatenating Tokens with the ## Operator Following illustrates the ## operatorVar1 is Using Macros to Define ConstantsOther Macros #define Arraysize 1000float xARRAYSIZEUsing Constants and Inline Functions Instead of Macros Assertions #assert, #unassert Predefined MacrosHP aC++ predefines the following predicates Conditional Compilation #if, #ifdef, .. #endifCode that compiles if the expression evaluates to zero Using the #ifdef and #ifndef Directives Using the defined OperatorUsing the #if Directive Using the #else DirectiveExample Line Control #line#line 5 myfile Pragma Directive #pragma and Pragma Operator This macro enables the following non-standard featuresIostream Performance Improvement Pragma See page 96 for more information on pragmasExamples Error Directive #errorTrigraph Sequences Line below contains the trigraph sequence ??=When this line is compiled it becomes ??=line 5 myfileScope and Precedence Using HP aC++ TemplatesInvoking Compile-Time Instantiation Template ProcessingPerformance Explicit InstantiationUsage Template class TablecharFunction Template Command-Line Option InstantiationCompile-Time Instantiation ACC -c +instcompiletime a.C ACC -c a.CPossible Duplicate Symbols in Archive Libraries Why Use Compile-Time InstantiationPossible Duplicate Symbols in Shared Libraries ScopeBuilding an Archive Library with +instauto/+instclose ++ Template TutorialClass Templates Building an Archive Library with Compile-time InstantiationFunction Templates Bool Keyword Standardizing Your CodeHP aC++ Keywords HP aC++ KeywordsCompile time error message is Dynamiccast KeywordAbove generates a compile-time error Explicit Keyword Classic example of this problem is an array class Mutable Keyword Namespace and using Keywords Connections Across Translation UnitsAn Auxiliary Translation Unit Using- declarations and using- directivesUsing Nx // Where N is a namespace, x is a name in N IntPage Class Base Virtual void f Must have a virtual function to Volatile Keyword Template Keyword Wchart KeywordTypename Keyword Use it as the name of the template C below Overloading new and delete for ArraysDeclare a class as a member of the class template C2 below Example Standard Exception Classes RangeerrorInvalidargument Typeinfo Class Exceptions Thrown by the Standard C++ LibraryFollowing exceptions are thrown by the Standard C++ Library Unsupported Functionality Int before const typeinfo& constMemfun1reft Memfunreft Iostream Requesting Optimization Setting Basic Optimization LevelsOptimizing HP aC++ Programs Level 1 OptimizationLevel 4 Optimization Additional Options for Finer ControlLevel 3 Optimization Enabling Aggressive OptimizationsEnabling Only Conservative Optimizations Removing Compilation Time Limits When OptimizingProfile-Based Optimization Limiting the Size of Optimized CodeMaintaining Profile Data Files InstrumentationCollecting Data for Profiling Sample.exe input.file1 Sample.exe input.file2ACC -o sample.exe +Oprofile=use +O3 sample.C Pragmas That Control OptimizationPerforming Profile-Based Optimization See Optimization Pragmas page 103 for more informationException Handling Exception Handling in C++Basic Exception Handling Example Function Try Block ExamplesDebugging Exception Handling Performance Considerations Using ThreadsUsing Locks Rogue Wave Standard C++ LibraryRogue Wave Standard C++ Library 1.2.1 and Tools.h++ Required Command-line OptionsRogue Wave Standard C++ Library LpthreadThis option applies only to kernel threadsLimitations Using -DTHREADSAFE with the cfront Compatible libstreamUsing -DHPACCTHREADSAFERBTREE Cout endlException Handling Pthreads Posix ThreadsACC -mt prog.c Function Scoping Parallel Programming Using OpenMPOpenMP Implementation OpenMP Library OpenMP Header FileOpenMP APIs are defined in the library libomp Openmp Macro +Onoopenmp Command Line OptionEnvironment Variables in OpenMP Where, kind is either of of static, dynamic, or guidedExport OMPDYNAMIC=value Setenv Ompdynamic value Runtime Library Functions in OpenMPExecution Environment Functions Export OMPNESTED=value Setenv Ompnested valueOmpgetmaxthreads OmpsetnumthreadsOmpgetnumthreads OmpgetthreadnumOmpgetdynamic Lock FunctionsOmpsetdynamic OmpsetnestedOmpsetlock and ompsetnestlock Ompinitlock and ompinitnestlockOmpdestroylock and ompdestroynestlock Ompunsetlock and ompunsetnestlockOmpgetwtime Timing FunctionsOmptestlock and omptestnestlock Functions OmpgetwtickTools and Libraries HP Specific Features of lex and yaccCreating and Using Libraries Locale directive for lexStandard C++ Library Introduction to Using the Standard C++ LibraryHP aC++ Libraries IntroductionDifferences between Standard C++ Library and Other Libraries Non-Object-Oriented Design of the Standard C++ LibraryStandard C++ Library Reference Incompatibilities Between the Library and the StandardHP aC++ Runtime Support Library ACC -DHPACCUSINGMULTIPLIESINFUNCTIONAL test.cTools.h++ Library IOStream LibraryLinking with Shared or Archive Libraries Creating and Using Shared LibrariesLinking to C++ Libraries Specifying Other LibrariesCreating a Shared Library Using a Shared LibraryExample of Creating and Using a Shared Library Linking Archive or Shared LibrariesForcing the Export of Symbols in main Advanced Shared Library FeaturesUpdating a Shared Library Routines and Options to Manage C++ Shared Libraries Binding TimesSide Effects of C++ Shared Libraries Linker Options to Manage Shared LibrariesStandard HP-UX Libraries and Header Files Allocation Policies for ContainersFor -AA Standard Library For a string typeHP aC++ File Locations HP aC++ Executable FilesUsr/lib/hpux##/libCsup.so HP aC++ Runtime Libraries and Header FilesUsr/lib/hpux##/libCsup11.so ISO C++11 standard compliant Calling Other Languages Mixing C++ with Other LanguagesData Compatibility between C and C++ Syntax of extern C Using the extern C Linkage SpecificationHP aC++ Calling HP C Examples of extern CMain Function Differences in Argument Passing ConventionsExamples HP aC++ Calling HP C Running the Example HP C Calling HP aC++Enter the nameJoann Joann has a balance To compile the example, run the following commands Compiling and Running the Sample ProgramsFunction Naming Conventions Using Reference Variables to Pass ArgumentsCalling HP Fortran 90 from HP aC++ Example of Reference Variables as ArgumentsArrays Using extern C LinkageStrings Files in FortranDistributing Your C++ Products Applications that use HP aC++ Shared LibrariesLinking Your HP aC++ Libraries with Other Languages Installing your ApplicationHP aC++ Files You May Distribute Terms for Distribution of HP aC++ Files Getting Started with Migration Migrating from HP C++ cfront to HP aC++General Guidelines for Migration CC +p cfrontfile.CWriting Code for both Compilers Command-Line DifferencesNew Command-Line Options Explicit Loading and Unloading of Shared LibrariesObsolete Command-Line Options Describes obsolete command-line options for HP aC++Changed Command-Line Options PtvException Handling is the Default Migration Considerations when DebuggingMigration Considerations when Using Exception Handling See Debugging Options page 35 for complete informationPossible Differences when Exiting a Signal Handler Memory Allocation Failure and operator newDifferences in setjmp/longjmp Behavior Calling unexpectedUnreachable catch Clauses Throwing an Object having an Ambiguous Base ClassMigration Considerations when Using Libraries Standards Based LibrariesManip3C++ iostream manipulators HP C++ cfront Compatibility LibrariesFstream3C++ iostream and streambuf specialized to files Man 3s filebufHP C++ cfront Task Library Not Supported Migration Considerations Related to PreprocessingHP C++ cfront Complex Library Not Supported Replace #include with complexChanges in C++ Semantics Migration Considerations Related to StandardizationObsolete Preprocessor Options Implicit Typing of Character String LiteralsOverload Resolution Ambiguity of Subscripting Operator Execution Order of Static Constructors in Shared LibrariesMore Frequent Inlining of Inline Code Changes in C++ SyntaxExplicit int Declaration Equivalent, valid HP aC++ code follows For Statement, New Scoping RulesStruct as Template Type Parameter is Permitted WC,-ansiforscope,onTokens after #endif This code compiles without error with HP aC++Base Template Class Reference Syntax Change Overload not a KeywordStatic Member Definition Required Dangling Comma in enumDeclaring friend Classes Duplicate Formal Argument Names Using in Class DefinitionsIncorrect Syntax for Calls to operator new Ambiguous Function or Object DeclarationOverloaded Operations ++ Reference InitializationCompiling this code HP aC++ generates the following error Using operator new to Allocate ArraysOn HP aC++, the following error is generated Parentheses in Static Member Initialization ListQualified-id Required in Static Member Initialization List Non-constant Reference InitializationDigraph White Space Separators Migration Considerations when Using TemplatesVerbose Template Processing Information CA aCommon Template Migration Syntax Changes Converting Directed Mode to Explicit InstantiationCfront Implicit Include Convention Documentation feedback AC++ Message Catalog Diagnostic MessagesFrequently Encountered Messages Glossary AggressiveInternational Standard defines only synchronous exceptions See template Glossary Symbols IndexCrootdir FLOATTRAPSON, 103 FREQUENTLYCALLED, 106 HDRSTOP, 107 Hidden Index
Related manuals
Manual 15 pages 49.53 Kb