HP C/aC++ for PA-RISC Software manual Memory Allocation Failure and operator new

Page 203

calls made through a callback mechanism). If such calls do exist, and an exception is thrown, the unwinding can cause:

non-destruction of local objects (including compiler generated temporaries)

memory leaks when destructors are not executed

runtime errors when no catch clause is found

Memory Allocation Failure and operator new

In HP aC++ programs, when either operator new ( ) or operator new [ ] cannot obtain a block of storage, a bad_alloc exception results. This is required by the ANSI/ISO C++ International Standard.

In HP C++, memory allocation failures return a null pointer (zero) to the caller of operator new ().

To handle memory allocation failures in HP aC++ and to avoid a program abort, do one of the following:

Write try or catch clauses to handle the bad_alloc exception.

Use the nothrow_t parameter to specify the type when calling operator new and check for a null pointer.

Example:

operator new (size_t size, const nothrow_t &) throw(); operator new [] (size_t size, const nothrow_t &) throw();

.

.

.

#include <new.h> #include <stdexcept>

class X{};

 

void foo1() {

 

X* xp1 = new(nothrow())X;

// returns 0 when creating a nothrow

 

// object, if space is not allocated

}

 

void foo2() {

 

X* xp2 = newX:

// may throw bad_alloc

}

 

int main() {

 

try { foo1(); foo2();

}

catch (bad_alloc) {

// code to handle bad_alloc

}

catch(...) {

// code to handle all other exceptions

}

}

Possible Differences when Exiting a Signal Handler

Behavior when exiting a signal handler through a throw may differ between the two compilers.

Migration Considerations when Using Exception Handling 203

Image 203
Contents HP aC++/HP C A.06.28 Programmers Guide Page Contents +FP Contents Contents Contents Data Alignment Pragmas Pragma Directives and AttributesInitialization and Termination Pragmas Copyright Notice and Identification 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 ConventionsHP-UX 11i Releases Publishing HistoryRelated Documents HP-UX Release Name and Release IdentifierFollowing is a list of documents available with this release HP Encourages Your CommentsOther HP aC++ executable files are Getting Started with HP aC++Components of the Compilation System C89 C99 ecom CtcomDebugging Programs Using the aCC CommandCompiling a Simple Program Executing the ProgramExamples of the aCC Command Compiler Command Syntax and Environmental VariablesPreprocessed Source Files .i Files Files on the aCC Command LineAssembly Language Source Files .s Files ++ Source File .C fileLibrary Files .a and .so Files Configuration Files .conf FilesEnvironment Variables Object Files .o FilesCclibdir Environment Variable ACCFULLPATHNAMES Environment VariableACCMAXERR Environment Variable Cxxopts Environment VariableACC -L/mnt/proj/lib file.o ACC file.o Ccrootdir Environment VariableExport CCROOTDIR=/mnt/CXX2.1 Floating InstallationCxxmapfile Environment Variable Tmpdir Environment VariableHP aC++ Setting up Floating InstallationCommand-Line Options ILP32 Data Model and LP64 Data Model Options to Control Code GenerationACC -c sub.C prog.C ACC +DO11.22 +O3 app.CCompiling in Networked Environments Using +DS to Specify Instruction SchedulingSize and Alignment of HP Compiler Data Types Data Alignment and StorageACC -S prog.C ACC +u1 app.C Debugging OptionsFshort-enums +expandtypesindiag+macrodebug When to use -g, -g0, and -g1Differences Between -g, -g0, and -g1 Options G1 AlgorithmLocal +noobjdebug+pathtrace +pathtrace=kindACC +p file.C Error HandlingNone +pathtrace=globallocal+Wcontextlimit +wn+Wargs +Wv +wperfadvice+We +Weargs+noeh Exception HandlingExtensions to the Language +wsecurity+Onocxlimitedrange +OnofenvaccessFloating-Point Processing Options +decfp FpevalFpevaldec Nofpwidetypes+Onopreservedfpregs +FPmode+Onolibmerrno +OprefetchlatencyHeader File Options ACC -I include file.C Idirs -I- -Idirs +help Online Help Option+inlinelevel num Inlining OptionsLname Library OptionsDynamic Exec+Onolibcalls= Linker OptionsMinshared +nostl+Onodynopt UsymbolUsymbol +Onodynopt+ildrelink Options for Naming the Output FileNative Language Support Option +ildACC -z file.C Handling Null Pointers OptionsCode Optimizing Options Basic Optimization Level Options+O3 +O0+O1 +O2+O4 Additional Optimization Options for Finer Control+O4 ACC +O3 prog.C+Onofailsafe Ipo+nonrv +Onoptrstoglobals=list Advanced +Ooptimization Options+Onoaggressive +Onolimit+Onofltacc +Onocrossregionaddressing+Onodatalayout +Onodataprefetch+Onoinitcheck +Ofrequentlycalled+Ointegeroverflow +Onoinline+Olit +Onoopenmp +Olevel+Onolooptransform +Onoloopunroll+Onoprocelim +opts+Onoparminit +Onoparmsoverlap+Oshortdata +Orarelycalled+Onosignedpointers +Ounrollfactor +OtypesafetyProfile-Based Optimization Options +OnostoreorderingAnnotate=structs Parallel Processing OptionsInformation Embedding Options Displaying Optimization InformationRequired if -DPOSIXCSOURCEis used Option Matrix for -mt+tls=staticdynamic +Onoautopar+Ofast Performance Options+wlock Fast+DSmodel +Ofaster+Onotlscallschangetp +nosrcpos+uc Porting Options+sb +ubThis warning can be suppressed by adding an extra cast +w64bit+wdriver +wendianRedirecting Output From This Option Preprocessor OptionsDname Examples Maked+Maked +maked+profilebucketsize Profiling Code OptionsUname +check=none Runtime Checking Options+check +check=allCompiling 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=truncateimplicit +check=truncateexplicitimplicit+check=uninit Ch = intval & 0xff +check=truncateexplicitAarm Standards Related OptionsAarm Agcc AC89AC99 Ag+++legacyv5 AOa and -AOe+legacycpp +stl=rwnone +std=c89c99c++98c++11gccg++gnu+tru64 +tru64Wc,-ansiforscope,onoff Wc,-koeniglookup,onoffTx,name Subprocesses of the CompilerTx,name More Examples of -tWx,args Passing Options to the Linker with -W Symbol Binding OptionsBdefault BexternBprotecteddata BhiddenBhiddendef BprotectedTemplate 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 align N Data Alignment Pragmas#pragma Versionid string #pragma Versionid Software Product, Version 12345.A.01.05Data 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 T2Floattrapson Pragma Optimization PragmasOptlevel Pragma Optimize PragmaNoinline Pragma Other Pragmas Diagnostic PragmasExtern Pragma Defaultbinding PragmaBinding Pragma Estimatedfrequency PragmaHpdefinedinternal Pragma Hdrstop PragmaHidden Pragma Hpdefinedexternal PragmaPtrsstronglytyped Pragma POP PragmaPragma once Protected PragmaStdc Fpcontract Pragma #pragma Stdc FLOATCONSTDECIMAL64 on OFF DefaultStdc Cxlimitedrange Pragma Stdc FLOATCONSTDECIMAL64 PragmaOMP Atomic Pragma Stdc Fenvaccess PragmaUnrollfactor Pragma OMP Flush Pragma OMP Barrier PragmaOMP Critical Pragma OMP for PragmaOMP Parallel for Pragma OMP Master PragmaOMP Ordered Pragma OMP Parallel PragmaOMP Task Pragma OMP Parallel Sections PragmaOMP Sections Pragma OMP Single PragmaOpenMP Clauses Copyin DefaultCopyprivate SharedAttributes Attribute noreturn Attribute nonexposingAttribute noreturn Attribute nonexposingAttribute warnunusedresult Attribute formatAttribute visibility Usage Guidelines Preprocessing DirectivesOverview of the Preprocessor SyntaxAssertions #assert, #unassert Source File Inclusion #include, #includenextSyntax DescriptionMacros with Parameters Macro Replacement #define, #undef#define mac very very long\ Replacement string ExamplesFollowing illustrates the ## operator Specifying String Literals with the # OperatorConcatenating Tokens with the ## Operator Example#define Arraysize 1000float xARRAYSIZE Using Macros to Define ConstantsOther Macros Var1 isUsing 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 #else Directive Using the defined OperatorUsing the #if Directive Using the #ifdef and #ifndef Directives#line 5 myfile Line Control #lineExample See page 96 for more information on pragmas This macro enables the following non-standard featuresIostream Performance Improvement Pragma Pragma Directive #pragma and Pragma OperatorLine below contains the trigraph sequence ??= Error Directive #errorTrigraph Sequences Examples??=line 5 myfile When this line is compiled it becomesTemplate Processing Using HP aC++ TemplatesInvoking Compile-Time Instantiation Scope and PrecedenceTemplate class Tablechar Explicit InstantiationUsage PerformanceACC -c +instcompiletime a.C ACC -c a.C Command-Line Option InstantiationCompile-Time Instantiation Function TemplateScope Why Use Compile-Time InstantiationPossible Duplicate Symbols in Shared Libraries Possible Duplicate Symbols in Archive LibrariesBuilding an Archive Library with Compile-time Instantiation ++ Template TutorialClass Templates Building an Archive Library with +instauto/+instcloseFunction Templates HP aC++ Keywords Standardizing Your CodeHP aC++ Keywords Bool KeywordDynamiccast 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 KeywordsInt Using- declarations and using- directivesUsing Nx // Where N is a namespace, x is a name in N An Auxiliary Translation UnitPage 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 Level 1 Optimization Setting Basic Optimization LevelsOptimizing HP aC++ Programs Requesting OptimizationEnabling Aggressive Optimizations Additional Options for Finer ControlLevel 3 Optimization Level 4 OptimizationLimiting the Size of Optimized Code Removing Compilation Time Limits When OptimizingProfile-Based Optimization Enabling Only Conservative OptimizationsSample.exe input.file1 Sample.exe input.file2 InstrumentationCollecting Data for Profiling Maintaining Profile Data FilesSee Optimization Pragmas page 103 for more information Pragmas That Control OptimizationPerforming Profile-Based Optimization ACC -o sample.exe +Oprofile=use +O3 sample.CException Handling in C++ Exception HandlingFunction Try Block Examples Basic Exception Handling ExampleRogue Wave Standard C++ Library Using ThreadsUsing Locks Debugging Exception Handling Performance ConsiderationsLpthreadThis option applies only to kernel threads Required Command-line OptionsRogue Wave Standard C++ Library Rogue Wave Standard C++ Library 1.2.1 and Tools.h++Cout endl Using -DTHREADSAFE with the cfront Compatible libstreamUsing -DHPACCTHREADSAFERBTREE LimitationsACC -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 Where, kind is either of of static, dynamic, or guided +Onoopenmp Command Line OptionEnvironment Variables in OpenMP Openmp MacroExport OMPNESTED=value Setenv Ompnested value Runtime Library Functions in OpenMPExecution Environment Functions Export OMPDYNAMIC=value Setenv Ompdynamic valueOmpgetthreadnum OmpsetnumthreadsOmpgetnumthreads OmpgetmaxthreadsOmpsetnested Lock FunctionsOmpsetdynamic OmpgetdynamicOmpunsetlock and ompunsetnestlock Ompinitlock and ompinitnestlockOmpdestroylock and ompdestroynestlock Ompsetlock and ompsetnestlockOmpgetwtick Timing FunctionsOmptestlock and omptestnestlock Functions OmpgetwtimeLocale directive for lex HP Specific Features of lex and yaccCreating and Using Libraries Tools and LibrariesIntroduction Introduction to Using the Standard C++ LibraryHP aC++ Libraries Standard C++ LibraryNon-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 ReferenceIOStream Library ACC -DHPACCUSINGMULTIPLIESINFUNCTIONAL test.cTools.h++ Library HP aC++ Runtime Support LibrarySpecifying Other Libraries Creating and Using Shared LibrariesLinking to C++ Libraries Linking with Shared or Archive LibrariesLinking Archive or Shared Libraries Using a Shared LibraryExample of Creating and Using a Shared Library Creating a Shared LibraryUpdating a Shared Library Advanced Shared Library FeaturesForcing the Export of Symbols in main Linker Options to Manage Shared Libraries Binding TimesSide Effects of C++ Shared Libraries Routines and Options to Manage C++ 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 Examples of extern C Using the extern C Linkage SpecificationHP aC++ Calling HP C Syntax 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 commandsExample of Reference Variables as Arguments Using Reference Variables to Pass ArgumentsCalling HP Fortran 90 from HP aC++ Function Naming ConventionsFiles in Fortran Using extern C LinkageStrings ArraysApplications 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 CC +p cfrontfile.C Migrating from HP C++ cfront to HP aC++General Guidelines for Migration Getting Started with MigrationExplicit Loading and Unloading of Shared Libraries Command-Line DifferencesNew Command-Line Options Writing Code for both CompilersDescribes obsolete command-line options for HP aC++ Obsolete Command-Line OptionsPtv Changed Command-Line OptionsSee Debugging Options page 35 for complete information Migration Considerations when DebuggingMigration Considerations when Using Exception Handling Exception Handling is the DefaultMemory 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 LibrariesMan 3s filebuf HP C++ cfront Compatibility LibrariesFstream3C++ iostream and streambuf specialized to files Manip3C++ iostream manipulatorsReplace #include with complex Migration Considerations Related to PreprocessingHP C++ cfront Complex Library Not Supported HP C++ cfront Task Library Not SupportedImplicit Typing of Character String Literals Migration Considerations Related to StandardizationObsolete Preprocessor Options Changes in C++ SemanticsExecution Order of Static Constructors in Shared Libraries Overload Resolution Ambiguity of Subscripting OperatorExplicit int Declaration Changes in C++ SyntaxMore Frequent Inlining of Inline Code WC,-ansiforscope,on For Statement, New Scoping RulesStruct as Template Type Parameter is Permitted Equivalent, valid HP aC++ code followsOverload not a Keyword This code compiles without error with HP aC++Base Template Class Reference Syntax Change Tokens after #endifDeclaring friend Classes Dangling Comma in enumStatic Member Definition Required Ambiguous Function or Object Declaration Using in Class DefinitionsIncorrect Syntax for Calls to operator new Duplicate Formal Argument NamesReference Initialization Overloaded Operations ++Parentheses in Static Member Initialization List Using operator new to Allocate ArraysOn HP aC++, the following error is generated Compiling this code HP aC++ generates the following errorNon-constant Reference Initialization Qualified-id Required in Static Member Initialization ListCA a Migration Considerations when Using TemplatesVerbose Template Processing Information Digraph White Space SeparatorsCfront 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