Traps and pitfalls for VC6, ATL, C++ May be obvious ? May be not ? Mark Bartosik.

Slides:



Advertisements
Similar presentations
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Advertisements

What's new in Microsoft Visual C Preview
R4 Dynamically loading processes. Overview R4 is closely related to R3, much of what you have written for R3 applies to R4 In R3, we executed procedures.
1 Lecture 4: Procedure Calls Today’s topics:  Procedure calls  Large constants  The compilation process Reminder: Assignment 1 is due on Thursday.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 Names, Scopes and Bindings. 2 Names Kinds of names Kinds of names Variables, functions, classes, types, labels, blocks, operators, tasks, etc. Variables,
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
. Memory Management. Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
KEAN UNIVERSITY Visual C++ Dr. K. Shahrabi. Developer studio Is a self-contain environment for creating, compiling, linking and testing windows program.
File System. NET+OS 6 File System Architecture Design Goals File System Layer Design Storage Services Layer Design RAM Services Layer Design Flash Services.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 192 Lecture 3 Winter 2003 December 5, 2003 Dr. Shafay Shamail.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
Natalia Yastrebova What is Coverity? Each developer should answer to some very simple, yet difficult to answer questions: How do I find new.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
© 2003 Mark Bartosik, Dealing with Leaks.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Writing a Run Time DLL The application loads the DLL using LoadLibrary() or LoadLibraryEx(). The standard search sequence is used by the operating system.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Computer Graphics 3 Lecture 1: Introduction to C/C++ Programming Benjamin Mora 1 University of Wales Swansea Pr. Min Chen Dr. Benjamin Mora.
Inheritance and Composition Reusing the code and functionality Unit - 04.
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Text Introduction to.NET Framework. CONFIDENTIAL Agenda .NET Training – Purpose  What is.NET?  Why.NET?  Advantages  Architecture  Components: CLR,
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Today: –Two simple binding examples. –Function Hiding.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Advanced BioPSE NCRR Programming Conventions and Standards J. Davison de St. Germain Chief Software Engineer SCI Institute December 2003 J.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
Boris Jabes Program Manager Visual C++ Microsoft Corporation.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
Some of the utilities associated with the development of programs. These program development tools allow users to write and construct programs that the.
Duke CPS Iterators: Patterns and STL l Access a container without knowing how it’s implemented ä libtapestry: first, isDone, next, current iterators.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
C++ Lesson 1.
Asst.Prof.Dr. Tayfun ÖZGÜR
VBA - Excel VBA is Visual Basic for Applications
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
CS 215 Final Review Ismail abumuhfouz Fall 2014.
C++ Templates.
Data types Data types Basic types
7. Inheritance and Polymorphism
COM S 326X Deep C Programming for the 21st Century Prof. Rozier
Checking Memory Management
Pointers and References
Reserved Words.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Variables, Identifiers, Assignments, Input/Output
Prof. Bhushan Trivedi Director GLS Institute of Computer Technology
Binding Times Binding is an association between two things Examples:
SPL – PS1 Introduction to C++.
SPL – PS3 C++ Classes.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Traps and pitfalls for VC6, ATL, C++ May be obvious ? May be not ? Mark Bartosik

Danagers of _bstr_t _bstr_t::_bstr_t(const char * narrow_str) –Unhandled exception 0xC00000FD because it allocates from the stack 2 x strlen(narrow_str) operator const char *() const operator char *() –both return a pointer to PRIVATE data const char * p = get_str(); unsigned len = strlen(p); // bang ???#! error ??

Danagers of _bstr_t operator const wchar_t *() const operator wchar_t *() –both return a pointer to PRIVATE data BSTR p = get_str(); unsigned len = SysStringLen(p); // bang ???#! err??

Alternatives with _bstr_t const wchar_t * GetWString() const const char * GetString() const But not realistic. Once the extraction operators exist, you cannot avoid them. #pragma depracated see Visual Studio.NET

Dangers of CComBSTR What is wrong with the following member functions? operator BSTR() const BSTR* operator&() int a; int * p = &a;

CComPtr CComQIPtr T** operator&() –Gives access to internal data can cause a leak (if not NULL) T& operator*() –Does not access to IUnknown operator->() returns proxy object with private IUnknown operator T*() –Gives implicit access to raw pointer

_com_ptr_t T** operator&() T* operator->() Exposes Iunknown, unlike CComPtr & CComQIPtr which return a proxy object Behaves like CComQIPtr but uses exceptions for error reporting. Auto declared by #import

variant_t : public VARIANT

How to choose ? Consistency is best Consistently use _bstr_t or CComBSTR Consistently use CComPtr or _com_ptr_t If using #import prefer _com_ptr_t Does the rest of your code use exceptions or magic return values? Write your own? (based on CComPtr)

collections std::map std::map > std::map > > Also when erasing elements, don’t saw off the branch that you are sitting on. (General STL rule) Store objects NOT dumb pointers (smart pointers are objects) Remember that my_collection.erase(iter) invalidates iter. use iter = my_collection.erase(iter) Don’t forget about the algorithms #include

#import Can use instead of.h, even for implementation Implement the raw_ functions. Read the.tlh files Be careful some functions will return IDispatchPtr others will return IDispatch *. It depends on the IDL. Reading the.tlh is a thinking aid, keep it open in a window.

Debugging Prefer __stdcall over __thiscall Optimizer off Consider releasing with optimizer off (except allow inlines for likes of STL) Symbol files on (PDB not PDB for edit continue), Link with debug info, Do not separate types Debug with Visual Studio.NET

(more) lifetime management CObj::foo() { CSLock __anonymous__(m_critsec); m_sub_object.Release(); } // Bang! CObj::foo() { IUnknownPtr __anonymous__(this); CSLock __anonymous__(m_critsec); m_sub_object.Release(); }

(more) lifetime management Do not mix strong and weak pointers What if you need a C++ pointer to a CComObject derived object? std::pair or struct { UnknownPtr strong_ref; COurClass * weak_ref; }

Patterns Avoid Singleton anti-pattern Once per what? Per network? Per sub-net? Per machine? Per apartment ? Per security context ? Per process? Per thread? Per transaction? Per user ? Etc. The ATL singleton is once per process. Use a more natural language idiom –C++ globals are naturally per process. –C variables in a shared data seg are naturally per machine –VB module variables are naturally per thread (apartment) –But avoid global pointers to COM objects (issues with CRT and COM initialization order)

Cyclic references & Connection points Wizard generated code is just bad (has some bugs) Also it is synchronous see (search for Bartosik) Lack of type safety (IDispatch)

Build consideration Prefer dynamic link CRT (but there are install issues) Avoid creating COM components within a group

Libraries STL WTL boost.org

Leak Browser Much of COM is about ownership / lifetime management, but poor C++ language binding, thus the bugs. Will find all your leaks Soon will find all your references to deleted objects Soon will find all use of uninitialized memory Contact Bartosik for updates / latest build.

casts reinterpret_cast (from) reinterpret the bit pattern (unsafe and forceful) dynamic_cast (from) runtime check (from must have at least one virtual function). Often a sign of bad design. Why don’t you know the type. dynamic_cast (base*) static_cast (from) convert only if reasonable const_cast (from) remove either const or volatile qualifiers (TO) c-style cast -- avoid it, like static_cast OR reinterpret_cast optionally combined with const_cast, and can be more forceful than reinterpret_cast.

Compiler settings (use PDB for all)

Linker settings (include debug info)

Linker settings (do not separate types)