Páginas

lunes, 25 de noviembre de 2013

Friday November 22, 2013

Today was our finall day of labs and we had to send our fives last programs. To me, they were the most dificult of all. I spent a lot of time working on the problem four. That problem was the most I liked of all, because it was very similar to the software that the library utilizes. I do not had the time to finish all fives problems but at least I could send three of them.
Wednesday November 20, 2013

Today we have almost 3 hours of lectures and some of the things that we discuss were the final of chapter 8 and started discussing chapter nine. We discuss in chapter eigth about vectors that are like arrays that can change size, how can we declare it and how we can use them in our sourcescodes. But in order to use them we need to include the library of vectors that is  #include <vector>. We ended the chapter discusing about controlling vector capacity and later on we starter discusing the basics about pointers. How can we utilizes, what is a pointer, what is the purpose of a pointer and how we can trackt it alongside with our code.

Friday November 15, 2013

One of the things we discuss in class today was the ignore. That is a member of the istream class and it can be utilize to read and eliminated all characters. But it takes two arguments: The first oe is the maximum number of characters to discard and the second is the character that stops reading and discarding. Also I learn that comparison operators also can work with string objects  = = and  returns true if two string objects contain the same characters in the same order. We can also transforms strings in c++ to c-trings.

Wednesday November 13, 2013

We started to see the that the variables of type string can be assigned with the = operator to assigned them a string of words. But the constructor initializes the string to the empty string if you donot initialize the variable when you declare it. We also recall that the cin skips the whitespace   to find what it is to read then stops reading and the versions of getline stop reading at the end of line marker. Later all we ended with the lacture and I started workin with my lab 7.



Microsoft updates C++ compiler

Update lets Visual Studio support some aspects of C++11

By Joab Jackson
November 5, 2012 12:15 PM ET
IDG News Service - Microsoft is updating its C++ compiler for its Visual Studio 12 integrated development environment, or IDE, so that Windows application developers can use parts of the latest version of the programming language, C++11.
Friday afternoon, Herb Sutter, secretary of the ISO/ANSI C++ Standards Committee as well as a Microsoft platform evangelist, announced the release of the new batch compiler during a talk about the future of the language at the Microsoft Build conference, held in Redmond, Washington,
The company has released a compiler CTP (community technology preview) that supports some of the features in the latest C++, including variadic templates, uniform initialization and initializer_lists, delegating constructors, raw string literals, explicit conversion operators and default template arguments for function templates.
The release is the first of what will be a series of "out-of-band" releases, which periodically update the Visual Studio IDE with new features in between major releases, Sutter said. Microsoft will release additional C++ functionality in early 2013 in future out-of-band updates, Sutter said.
The CTP requires Microsoft Visual Studio 12 to run, though it can be run in a free version of the IDE, Desktop Express. Visual Studio 2012 built-in tools, such as Intellisense, debugger and static analysis do not yet support the new C++ features.
"We updated the batch compiler [but] the standard library has not been yet updated, so some of the new features that the standard library could use haven't been lit up yet," Sutter said. "That's just for the CTP. When we ship it, all those features will be in place."
Sutter said that while Microsoft CTPs tend to be pretty stable, it would not be advisable to use the compiler to produce production-ready programs.
As Sutter noted during his talk, there has been a lot of activity around the programming language of late. Microsoft, Intel, Google, IBM and other members of the C++ Committee have formed the Standard C++ Foundation, which will provide educational materials and encourage the correct use of C++ across different compilers.
The standard group has also commenced work on the next generation of the C++ language, C++17, due in 2017.
Developed in Bjarne Stroustrup in 1979, C++ brought object oriented features to the C programming language. It remains one of the most widely used programming languages, and is often used for large scale applications where performance is a critical factor. "We are built on C++, just as the whole industry runs on C and C++," Sutter said, referring to how much of Microsoft's latest operating systems, Windows 8 and Windows RT, was written in C++.
Joab Jackson covers enterprise software and general technology breaking news for The IDG News Service. Follow Joab on Twitter at @Joab_Jackson. Joab's e-mail address is Joab_Jackson@idg.com

  • Low Level Languages:-
1. It is close to Machine language.
2. It is difficult to learn and use.
3. It is machine dependent
4. It does not provide built in functions.
5. Program written in low level language is faster in execution.
6. Deep knowledge of hardware is required to learn and use low level languages.
7. There are few programmers that can write programs in low level languages.
8. It is difficult to trace out errors in the programs written in low level language.
9. Low level languages are not commonly used.
10. The program statement written in low level language is very lengthy.
  • High Level Languages:- 
1. It is close to human language.
2. It is easy to learn and use.
3. It is not machine dependent.
4. It provides large number of built in functions.
5. Program written in high level language is slower in execution.
6. No deep knowledge is required to learn and use high level language.
7. There are many programmers that can write programs in high level language.
8. It is easy t trace out errors in the program written in high level language.
9. High level languages are commonly used.
10. The program statement written in high level language is very short.

Lower Level Languages and Higher Level Languages

Generally speaking higher level programming languages are closer to human spoken languages and lower level programming languages are closer to machine code, or binary. However this classification might not always be so clear. C++ is one language that some might argue challenge this programming language stereo type. C++ is a programming language that has all the features that one would expect from a higher level language such as an easy to read syntax, object oriented programming and extensive collections of libraries to add to the language's capabilities but also has other features that are not commonly found in higher level languages such as memory management, user defined operator overloading, six different integer datatypes and a plethora of compilers to choose from. As a result many refer to C++ as a mid-level programming language. 
For Processing this distinction is currently not so difficult to make. Processing is a high level language, meaning it has an easy to read syntax, supports modern day programming concepts such as Object Oriented Programming, has it's own IDE (Integrated Development Environment something we will become more familiar with throughout this guide) and fundamentally it abstracts a lot of machine specific interactions for us making the code more readable for humans.
However, it's worth considering that the terms “higher” and “lower” level programming languages are relative to the time period in which they are used. For example when the programming language C (that C++ is based on) was first introduced in the early 1970's it was considered to be a high level language as it supported such features as expression evaluation and datatyping, both of which are programming concepts common to most modern day programming languages. As technology progresses, new concepts become common place and rapidly replace older more cumbersome programming designs, till we get to the point where there are far less people that would refer to an older language such as C as being a high level language and a lot more people that would refer to it as a low level language, lacking modern abstractions and less direct hardware interactions. Processing might one day, also be subjected to such a topic of discussion.

Following is the C version of a “Hello World” Program:

#include <stdio.h>
int main(void)
{
    printf("hello, world\n");
    return 0;
}

The level of abstraction that is needed in order for a language to qualify as a higher level programming language does not come without it's penalties. Lower level languages, because they are conceptually closer to machine code are considered to produce more efficient machine readable code, of course this is largely dependent on the programmer creating the code. As mentioned before the greater the level of abstraction of the code, the more stress that is placed on the machine interpreting the code, and subsequently more system resources are required. As a result of this cycle higher level programming languages generally cannot run on systems where resources are limited. Initially, this might not seem like such a big issue to you, but have you ever considered the amount of technology running on limited resources like a television, fridge, GPS, mobile phone, remote-controlled air-conditioner, electronic toys, media players and the list goes on...? In fact if you were to think about it there are not many devices like computer workstations, laptops or computer servers that are designed to have their resources, available to the software that runs on these machines, extended. Yet, even these machines have their limitations.
Ultimately software, whether it is designed with a high level or low level programming language, should always take into consideration the possible limitations of available system resources.

Avoiding Pointer Problems in C++

Part of the Beginning Programming with C++ For Dummies Cheat Sheet

In C++, a pointer is a variable that contains the address of another variable in the computer's internal memory. Use these steps to avoid problems with pointers in C++:
  1. Initialize pointers when declared.
    Never leave pointer variables uninitialized - things wouldn't be too bad if uninitialized pointers always contained random values - the vast majority of random values are illegal pointer values and will cause the program to crash as soon as they are used. The problem is that uninitialized variables tend to take on the value of other, previously used pointer variables. These problems are very difficult to debug.
    If you don't know what else to initialize a pointer to, initialize it to zero. Zero is guaranteed to be an illegal address.
  2. Zero pointers out after you use them.
    Similarly, always zero a pointer variable once the pointer is no longer valid. This is particularly the case when you return a block of memory to the heap using delete; always zero the pointer after returning heap memory.
  3. Allocate memory from the heap and return it to the heap at the same "level" to avoid memory leaks.
    Always try to return a memory block to the heap at the same level of abstraction as you allocated it. This generally means trying to delete the memory at the same level of function calls.
  4. Catch an exception to delete memory when necessary.
    Don't forget that an exception can occur at almost any time. If you intend to catch the exception and continue operating (as opposed to letting the program crash), make sure that you catch the exception and return any memory blocks to the heap before the pointers that point to them go out of scope and the memory is lost.
  5. Make sure that the types match exactly.
    Always make sure that the types of pointers match the required type. Don't recast a pointer without some specific reason. Consider the following:
    void fn(int* p);
    void myFunc()
    {
        char c = 'a';
        char* pC = &c;
        fn((int*)pC);
    }
    The above function compiles without complaint since the character pointer pC has been recast to an int* to match the declaration of fn(int*); however, this program will almost surely not work. The function fn() is expecting a pointer to a full 32-bit integer and not some rinky-dink 8 bit char. These types of problems are very difficult to sort out.

The Usual C++ Header Files

Part of the C++ All-In-One For Dummies Cheat Sheet

In C++, a header file holds forward declarations of identifiers. Here are some of the most common C++ header files that you’ll be using, along with their correct spellings. These aren’t by any means all of them, but they are the most common:
  • Include <string> if you’re going to be using the string class.
  • Include <iostream> when you want to use cout and cin.
  • Include <fstream> when you want to read or write files.
  • Include <iomanip> if you want advanced manipulator usage in your streams.
  • Include <stdlib.h> for general operations, including system(“PAUSE”).

The Ten Most Common C++ Mistakes

Part of the C++ All-In-One For Dummies Cheat Sheet

Although many C++ programmers take measures to prevent bugs, mistakes still slip through. This list of the ten most common mistakes while writing C++ code can help both new and veteran programmers:
  1. You forgot to declare the variable.
  2. You used the wrong uppercase and lowercase letters; for example, you typed Main when you meant main.
  3. You used one equal sign (=) when you were supposed to use two (==), either in an ifstatement or in a for loop.
  4. You forgot #include <iostream> or using namespace std;.
  5. You dropped the laptop in the swimming pool.
  6. You forgot to call new and just started using the pointer anyway.
  7. You forgot the word public: in your classes so everything turned up private.
  8. You let the dog eat the remote.
  9. You forgot to type the parentheses when calling a function that takes no parameters.
  10. You forgot a semicolon, probably at the end of a class declaration.

Should Developers Start Learning C++?

by Jonathan Allen on Dec 06, 2012 | 9 Discuss
With the introduction of C++ 11 and C++ CX there has been a lot of renewed interest in the language. And a lot of developers, especially Windows developers, are wondering if they should set aside C# and Java in favor of it. John Sonmez argues no.
In his article titled Why C++ Is Not ‘Back’, John Sonmez argues that there are only three reasons to use C++:
  • You absolutely need to ink out every bit of performance possible out of your software and you would like to do that with a language that will support OO abstractions.
  • You are writing code which will directly interface with raw hardware.  (Example: you are writing a low level driver.)
  • Memory control and timing is of absolute importance, so you must have completely deterministic behavior in your system and the ability to manually manage memory.  (Think real time embedded operating system controlling a moving piece of machinery.)
Herb Sutter, who has heavily praised this article for offering a “a thoughtful hype-free opinion” adds to the list:
  • Servicing, which is harder when you depend on a runtime.
  • Testing, since you lose the ability to test your entire application (compare doing all-static or mostly-static linking with having your application often be compiled/jitted for the first time on an end user’s machine).
One of the reasons that John Sonmez offers against learning C++ is the sheer complexity of the language. Even though C++ 11 has made development easier, it doesn’t excuse the programmer from learning all of the old ways of writing C++ code. “You will encounter C++ code from 20 years ago and it will look like a different language entirely.” To reinforce his point he posted the 36 questions he asked candidates for a C++ developer position. Here are a couple of examples,
1. How many ways are there to initialize a primitive data type in C++ and what are they?
12. What is a copy constructor and when is it used, especially in comparison to the equal operator.
16. When is it and when is it not a good idea to return a value by reference in C++?
33. Why should you never throw an exception in a destructor?
Another argument against C++ is that “programming languages really need to get simpler and increase the level of abstraction not reduce it.” He continues,
There will always be a need for low level code, but a majority of the code that we write today is at a much higher level.
I first jumped off the C++ ship many years ago when I finally could no longer make the argument that I could develop apps faster in C++ than C#.
I held out for a long time trying to believe that all the investment I had made in C++ was not lost, but it turned out that C# simplified things to such a great degree that the extra power C++ gave me was not worth the extra responsibility.
John Sonmez concludes by saying that learning C++ is still useful for understanding how computers work in general, “but I don’t think it is going to make a comeback any time soon, and that is a good thing.”
To this Alo adds,
I started out on C++ and spent the first four years of my career exclusively on C++. That experience has been extremely valuable for me down the line because – as you pointed out – once you learn C++ to an adequate level, you can pick up any other language really fast and you’ve developed a deeper understanding of how software works on a lower level – a knowledge that’s much harder to acquire when starting out at higher-level languages; I’ve always frowned upon the idea of starting programmers out on Java for that very reason.
Richard Dunks counters with,
I think C++ is unhelpful for use in first semester introduction to programming classes and in teaching data structures, you have to spend so much time on the implementation, the students often lose sight of the structure they’re trying to replicate. I’m glad I’ve gained the proficiency in C++, but I don’t think it’s worth the cost and definitely not a one-size fits all instructional language.
Stephen Cleary offers a comment on reusability,
I’m a former C++ master who became a C# developer a few years ago due to marketplace pressures. I am CERTAINLY more productive in C#, but it’s simply not possible to reach the same level of code reuse as you can with C++ templates.
The classic example is the triumvirate of containers, iterators, and algorithms. In C++, you can create one algorithm that will work with any container and adjust itself at compile time to take advantage of random access if necessary. Try doing that in C#. And I’m not talking about the “new C++” here, either; C++ permitted greater code reuse in 1998 than C# does today.
And in regards to performance, Herb Sutter offers this bit of advice,
In any language, if you are serious about performance you will be using arrays a lot (not “always,” just “a lot”). Some languages make that easier and give you much better control over layout in general and arrays in particular, while other languages/environments make it harder (possible! but harder) and you have to “opt out” or “work against” the language’s/runtime’s strong preference for pointer-chasing node-based data structures.
In additional to numerous high quality comments on Herb Sutter and John Sonmez’s respective blogs, there is much to be learned from Programming and Coding subgroups of Reddit.

Microsoft Visual Studio 2013 Review

I admit it: I've been an avid Visual Studio user since the IDE's introduction. The original product represented a major milestone for Microsoft because it brought together for the first time the company's collection of languages under one umbrella. Essentially, it became the Microsoft Office suite for developers. Nearly 15 years later, Visual Studio is the default development environment for developing Windows applications, ranging from traditional WinForms to the latest WinRT creations.

What's New?

Visual Studio 2013 (VS2013) is another release that adds important new technologies that I'll touch upon shortly. Among the most visible are some cosmetic changes, such as more than 400 modified icons that update the UI to a more colorful Windows 8 look. Others changes are nifty code editing efficiencies that appeared first in Visual Studio Power Tools add-ons, but are now officially integrated and supported. For example, editing improvements such as in-line code navigation and automatic bracket completion. But my favorite code editing improvement is the new scrollbar behavior: "Bar mode" is the traditional scrollbar operation, while "map mode" is something seen only in a few editors such as Sublime Text. In the VS2013 implementation, a miniaturized representation of the entire file being edited appears in a thin window down the right side of the edit panel (Figure 1). The map highlights the section of code that your cursor is located in and allows you to zoom in, thereby facilitating navigation in a large source file.
Figure 1: The new Map Bar feature that appears on the right of code-editing pages.
Other code enhancements include the in-line Peek Definition view from the Go To Definition context-sensitive menu option, automatic bracket completion, and the ability to move blocks of code via the a keyboard shortcut (which can be changed in the Tools -> Options -> Environment -> Keyboard dialog). Check out Microsoft's Visual Studio tips and tricks page for other useful keyboard shortcuts.
For Web development, the editor has been updated to support the latest HTML5 and CSS tags, and it is IntelliSense-enabled. And seeing how audio and video file elements dragged into the code window are wrapped inside appropriate HTML5 tag structures is a great help.
Another long overdue feature I was glad to see is VS2013's ability to edit-and-continue native 64-bit application debugging sessions. Considering that the majority of new enterprise applications are 64-bit, this improvement finally brings the 64-bit development experience to parity with the 32-bit step-debugging tools we have come to expect in any modern IDE.
On the code management front, the latest Team Foundation Server is supported along with the addition of the Git distributed SCM that has all but replaced Subversion as the default open-source code-management solution. And very helpful code changeset pop-ups embedded within the code quickly show exactly who wrote what (Figure 2).
Figure 2: Git support includes pop-up windows that show who did what.
There are a host of Windows 8.1-specific support enhancements as well, especially in the development of XAML-centric applications. For example, the XAML editor now supports a comprehensive set of IntelliSense options ranging from data and template binding, to finding references and Go To Definitions, to better integration with Microsoft's Azure Mobile Services for cloud-based hosting. Microsoft's standalone Blend designer tool also includes better styling and timeline capabilities to help speed up XAML interface development. And VS2013 now provides XAML performance analyzers to measure responsiveness, energy consumption, memory, and other metrics. They are especially helpful, though, in diagnosing delays in responses.
Figure 3: VS2013 offers performance analysis for XAML UI Responsiveness among other metrics.
Visual C++ has also received some well-deserved attention in VS2013, including better support for the C++11 specification (constructor delegation, explicit conversion operators, and variadic templates to name a few). A new Profile Guided Optimization leverages VS2013's improved profiling tools by allowing you to refine your C++ program based on visualizing the hotter and colder code paths.

Cloud And Web

VS2013 also supports Office 365 Cloud Business application development. With rumors swirling that a fully implemented Microsoft Office suite will one day make it to Android and iOS platforms, this technology has tantalizing possibilities for easy Office-centric ALM across a variety of mobile platforms.
Web development is another area where VS2013 has made ample improvements. ASP.NET developers will be pleased to discover that they can comfortably mix and match whatever framework they prefer (MVC, Web API, WebForms) in the same project. Gone are they days of segregating Web applications based on framework boundaries. Now, all of these technologies can operate happily together under the same umbrella.
Another nifty feature that will elicit a nod of satisfaction from Web developers is the new Browser Link capability. Browser Link keeps the latest browsers such as Internet Explorer, Chrome, and Firefox in sync with your code, showing design and behavior code changes in real-time. You can finally say goodbye to unnecessary button clicks, keypresses, and manual page refreshes.
VS2013 also expands support for new languages like TypeScript. TypeScript compiles down to JavaScript, but makes working with complex JavaScript-related operations far more manageable since TypeScript supports the full compliment of classes, interfaces, and modules that OOP programmers have come to rely on. VS2013 works with TypeScript just like it does with other languages by providing full support for code navigation and refactoring, statement auto-completion, and the like. And TypeScript can use popular JavaScript libraries such as Bootstrap and jQuery.

The New C++:Smart(er) Pointers

Last time [1], I gave a survey of the first batch of suggested library extensions that were considered at the October 2001 C++ standards meeting in Redmond, Washington, USA. This time, as promised, we'll take a closer look at one of the proposed facilities — smart pointers, which were discussed again at the following April 2002 standards meeting in Curaçao, in the Netherlands Antilles.

And Then There Was One

In today's Standard C++, there's only one smart pointer: std::auto_ptr.
Considering that it's such a tiny feature, auto_ptr sure has received copious attention. The main reason for the attention is that attention is deserved, both positively and negatively. On the one hand, auto_ptr is very useful for specific situations and those uses deserve to be described; see the discussion in Items 19 and 37 of Exceptional C++ [2], Item 10 of More Effective C++ [3], and my article "Using auto_ptr Effectively," available online [4]. On the other hand, auto_ptr can also be moderately suspicious to highly dangerous in other situations, such as the minefield of trying to put auto_ptrs into standard containers likevector and map; see for example Item 21 of More Exceptional C++ [5] and Item 28 of More Effective C++ [3]. (On the gripping hand, as Niven and Pournelle might say, auto_ptr relies on some fairly obscure language trickery to make it deliberately not work in some dangerous cases. Fortunately this trickery gets less press — the details are not for the faint of heart. Suffice it to say that auto_ptr is designed with some sleight of hand that's intended to make it deliberately break when used with, say, standard containers.)
So today's Standard C++ has exactly one smart pointer: auto_ptr. That's it. So it must be all you need, right? Not a bit of it. There's more to this story.
It's actually a real shame that auto_ptr is the only standard smart pointer, for at least two reasons. First, auto_ptr doesn't do all the useful things that smart pointers might be good for; there are many good uses of smart pointers that poor auto_ptr was never designed to support, and shouldn't, and doesn't. Second, auto_ptr can be a dangerous snake that turns and bites you on the hand if you do try to use it in some of those other ways.
The first piece of good news is that many good and useful smart pointers are available and were available even before auto_ptr. The only problem is that they weren't, and aren't, standard. That's somewhere between disappointing and annoying, depending on how portable your code needs to be — standard features are of course generally the most portable.
The second piece of good news is that those alternative smart pointers are now strong candidates for inclusion into the Standard. (Some could have been in the original Standard; see [1]. But better late than never.)

If One Is Good, Six Are Better... (?)

The Boost library ships with five additional smart pointers [6]. All of these smart pointer templates take a single type parameter specifying the type of the object to be held. Briefly, here they are:
  • scoped_ptr: a non-copyable smart pointer intended to be used as an auto (stack) object. When a scoped_ptr goes out of scope and is destroyed, it will automatically delete the single object it points to. Arguably, scoped_ptr is what auto_ptr ought to have been in the first place, way back when auto_ptr was first meant to be really an "auto" pointer. Butscoped_ptr doesn't support the modern auto_ptr's important additional usefulness for sources and sinks (described in [4]).
  • scoped_array: like scoped_ptr, but owns an array instead of a single object.
  • shared_ptr: a reference-counted smart pointer intended to be used to share "handles" to the pointed-at object. When a shared_ptr goes out of scope and is destroyed, if it is the last shared_ptr pointing at the owned object, it will automatically delete the owned object — a classic case of "last one out, turn off the lights." Note that shared_ptr does supportauto_ptr's important use for sources and sinks. More importantly, it can be safely used in a container, which for auto_ptrs is not allowed and highly dangerous.
  • shared_array: like shared_ptr, but owns an array instead of a single object.
  • weak_ptr: to be used in conjunction with a shared_ptr. If you have an object that's already managed by one or more shared_ptrs, you can create weak_ptrs to it too. Now, the shared_ptrs still follow the "last one out, turn off the lights" policy; the lastshared_ptr will delete the owned object even if there are still weak_ptrs to it. How isweak_ptr then any better than just a bald pointer to the object? Because the shared_ptrthat turns off the lights will also check to see if any weak_ptrs still point to that object and set them to null if they do. That's a level of safety you don't get with plain old raw pointers.
Let me repeat some advice from last time, because it's worth repeating: if you know nothing else about Boost, know about shared_ptr. It's especially valuable if you ever want to have a container of pointers, because what you almost always really want is a container ofshared_ptrs. For one thing, they'll be managed for you and will get cleaned up correctly, and they'll avoid the usual pitfalls of using mutating STL algorithms on containers of bald pointers. For another, they are not auto_ptrs, which is a Good Thing because auto_ptrs should never be put into STL containers.
The Boost approach is to have lots of special-purpose smart pointer types, one for each kind of smart pointer behavior. In this model, a smart pointer template is quite simple:
?
1
2
3
4
5
template<typename T> class scoped_ptr;
template<typename T> class scoped_array;
template<typename T> class shared_ptr;
template<typename T> class shared_array;
template<typename T> class weak_ptr;
Only one template parameter is needed, to specify the type of the owned object. It is both an advantage and a disadvantage that these little class templates can all have very different interfaces if they want to. On the one hand, it allows customization, say when a member function might make sense for one but not another smart pointer. But, on the other hand, it also means that it's easy to get inconsistent interfaces, especially when people start extending the facility by providing more smart pointers of their own, both within and outside the Boost library.

If Six Are Good, Infinity Is Better... (?!)

Although Boost chooses to follow the model of designing special-purpose smart pointer templates, we can ask: "Why stop there?" In fact, some very bright language designers, notably Andrei Alexandrescu in Modern C++ Design [7], have proposed that a "one size fits all" über-pointer may be an achievable dream, using policy-based design.
Policy-based design takes the view that certain details, such as checking policies and ownership policies, can be abstracted out into their own classes, which are then supplied as template parameters to configure or customize the basic smart pointer. Thus Loki's SmartPtrtemplate looks something like this:
?
1
2
3
4
5
6
7
8
9
template
<
  typename T,
  template <class> class OwnershipPolicy = RefCounted,
  class ConversionPolicy = DisallowConversion,
  template <class> class CheckingPolicy = AssertCheck,
  template <class> class StoragePolicy = DefaultSPStorage
>
class SmartPtr;
Note that we still have the obligatory template parameter T that describes the type of the pointed-at object. But we also get policies that govern much of the behavior of the smart pointer. The policies may look cumbersome to type out, but they are defaulted for those who don't want or need to specify them; the default Loki::SmartPtr is a lot like aboost::shared_ptr. In fact, SmartPtr covers all that the four basic Boost smart pointers can do, and more. (An equivalent of Boost's weak_ptr could also be provided to work with a partial specialization of SmartPtr corresponding to shared_ptr.)
Indeed, Loki's SmartPtr is so much a superset of Boost's smart pointers that we would love to just create synonyms. In Standard C++, the following code won't work because it relies on a feature that was frankly just overlooked, namely typedef templates (for some existing discussion, see [8]; I'll be writing more about this up-and-coming feature in the future). Barring major surprises, such as the Earth suddenly deciding to break out of its usual orbit and head for Mars on a holiday, typedef templates will be in the next C++ Standard, C++0x (see[9]). If we had this feature, we could write the following synonym:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
namespace boost {
  template<typename T>    // typedef templates aren't standard
  typedef Loki::SmartPtr  // yet, but let's overlook that for now...
    <
      T,                  // note, T still varies
      RefCounted,         // but everything else is fixed
      DisallowConversion,
      NoCheck,
      DefaultSPStorage
    >
 
    shared_ptr;
}
So that the usage would simply be, as usual:
?
1
shared_ptr<int> a;        // simple -- no fuss, no muss!
Similar synonyms could be created for shared_arrayscoped_ptrscoped_array, and evenstd::auto_ptr. Such simple names for common configurations would make all the tedious template parameters go away for those common cases. We can't do that today, alas, but once typedef templates become commonly available we will be able to do this and more.
SmartPtr really then describes an unlimited family of smart pointers having a consistent interface. Note that because Loki's SmartPtr inherits publicly from its template parameter types, the interface does not have to be identical across the whole family; the policies could add some visible functionality too. Loki already comes with several predefined policies allowing hundreds of combinations. But you can add your own policies, such as for managing COM and CORBA distributed objects and other advances uses, so the size of the SmartPtr family really is effectively unlimited.

Summary

The standards committee is still considering these options and welcomes other smart pointer submissions. In particular, there is ongoing discussion, with different points of view, about whether the "one size fits all" customizable policy-based design is the way to go, or whether just a few special-purpose smart pointer templates are needed. Want to weigh in? Start discussion on the Boost reflector [10] or on the comp.std.c++ newsgroup.
Next time: more news from the April 2002 standards meeting in Curaçao. Stay tuned.

References

[1] H. Sutter. "The New C++: The Group of Seven — Extensions under Consideration for the C++ Standard Library," C/C++ Users Journal C++ Experts Forum, April 2002, <www.cuj.com/experts/2004/sutter.htm>.
[2] H. Sutter. Exceptional C++ (Addison-Wesley, 2000).
[3] S. Meyers. More Effective C++ (Addison-Wesley, 1996).
[4] H. Sutter. "Using auto_ptr Effectively," C/C++ Users Journal, October 1999, available online at <www.gotw.ca/publications/using_auto_ptr_effectively.htm>.
[5] H. Sutter. More Exceptional C++ (Addison-Wesley, 2002).
[6] <www.boost.org/libs/smart_ptr/index.htm>
[7] A. Alexandrescu. Modern C++ Design (Addison-Wesley, 2001).
[8] H. Sutter. "Guru of the Week #79: Template Typedef," available online at <www.gotw.ca/gotw/079.htm>.
[9] H. Sutter. "The New C++," C/C++ Users Journal C++ Experts Forum, February 2002, <www.cuj.com/experts/2002/sutter.htm>.
[10] C++ Boost, <www.boost.org>.

About the Author

Herb Sutter (www.gotw.ca) is secretary of the ISO/ANSI C++ standards committee, author of the acclaimed books Exceptional C++ and More Exceptional C++, and one of the instructors of The C++ Seminar (www.gotw.ca/cpp_seminar). In addition to his independent writing and consulting, he is also C++ community liaison for Microsoft.