The C++ Programming Language

Bjarne Stroustrup

Mentioned 21

Offers information on using the C++ programming languge using the new C++11 standard, covering such topics as concurrency, facilities, standard libraries, and design techniques.

More on

Mentioned in questions and answers.

What is a lambda expression in C++11? When would I use one? What class of problem do they solve that wasn't possible prior to their introduction?

A few examples, and use cases would be useful.

One of the best explanation of lambda expression is given from author of C++ Bjarne Stroustrup in his book ***The C++ Programming Language*** chapter 11 (ISBN-13: 978-0321563842):

What is a lambda expression?

A lambda expression, sometimes also referred to as a lambda function or (strictly speaking incorrectly, but colloquially) as a lambda, is a simplified notation for defining and using an anonymous function object. Instead of defining a named class with an operator(), later making an object of that class, and finally invoking it, we can use a shorthand.

When would I use one?

This is particularly useful when we want to pass an operation as an argument to an algorithm. In the context of graphical user interfaces (and elsewhere), such operations are often referred to as callbacks.

What class of problem do they solve that wasn't possible prior to their introduction?

Here i guess every action done with lambda expression can be solved without them, but with much more code and much bigger complexity. Lambda expression this is the way of optimization for your code and a way of making it more attractive. As sad by Stroustup :

effective ways of optimizing

Some examples

via lambda expression

void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0
        [&os,m](int x) { 
           if (x%m==0) os << x << '\n';

or via function

class Modulo_print {
         ostream& os; // members to hold the capture list int m;
         Modulo_print(ostream& s, int mm) :os(s), m(mm) {} 
         void operator()(int x) const
             if (x%m==0) os << x << '\n'; 

or even

void print_modulo(const vector<int>& v, ostream& os, int m) 
     // output v[i] to os if v[i]%m==0
    class Modulo_print {
        ostream& os; // members to hold the capture list
        int m; 
           Modulo_print (ostream& s, int mm) :os(s), m(mm) {}
           void operator()(int x) const
               if (x%m==0) os << x << '\n';

if u need u can name lambda expression like below:

void print_modulo(const vector<int>& v, ostream& os, int m)
    // output v[i] to os if v[i]%m==0
      auto Modulo_print = [&os,m] (int x) { if (x%m==0) os << x << '\n'; };

Or assume another simple sample

void TestFunctions::simpleLambda() {
    bool sensitive = true;
    std::vector<int> v = std::vector<int>({1,33,3,4,5,6,7});

         [sensitive](int x, int y) {
             printf("\n%i\n",  x < y);
             return sensitive ? x < y : abs(x) < abs(y);

    for_each(v.begin(), v.end(),
             [](int x) {
                 printf("x - %i;", x);

will generate next











0 sortedx - 1;x - 3;x - 4;x - 5;x - 6;x - 7;x - 33;

[] - this is capture list or lambda introducer: if lambdas require no access to their local environment we can use it.

Quote from book:

The first character of a lambda expression is always [. A lambda introducer can take various forms:

[]: an empty capture list. This implies that no local names from the surrounding context can be used in the lambda body. For such lambda expressions, data is obtained from arguments or from nonlocal variables.

[&]: implicitly capture by reference. All local names can be used. All local variables are accessed by reference.

[=]: implicitly capture by value. All local names can be used. All names refer to copies of the local variables taken at the point of call of the lambda expression.

[capture-list]: explicit capture; the capture-list is the list of names of local variables to be captured (i.e., stored in the object) by reference or by value. Variables with names preceded by & are captured by reference. Other variables are captured by value. A capture list can also contain this and names followed by ... as elements.

[&, capture-list]: implicitly capture by reference all local variables with names not men- tioned in the list. The capture list can contain this. Listed names cannot be preceded by &. Variables named in the capture list are captured by value.

[=, capture-list]: implicitly capture by value all local variables with names not mentioned in the list. The capture list cannot contain this. The listed names must be preceded by &. Vari- ables named in the capture list are captured by reference.

Note that a local name preceded by & is always captured by reference and a local name not pre- ceded by & is always captured by value. Only capture by reference allows modification of variables in the calling environment.


Lambda expression format

enter image description here

Additional references:

I'm reading The C++ Programming Language, 4th Edition (by Bjarne Stroustrup) about . Here is the quote (26.3.6, Overaggressive ADL):

Argument-dependent lookup (often referred to as ADL) is very useful to avoid verbosity (14.2.4). For example:

#include <iostream>

int main()
    std::cout << "Hello, world" << endl; // OK because of ADL

Without argument-dependent lookup, the endl manipulator would not be found. As it is, the compiler notices that the first argument to << is an ostream defined in std. Therefore, it looks for endl in std and finds it (in <iostream>).

And here's the result produced by the compiler (C++11 mode):

prog.cpp: In function ‘int main()’:
prog.cpp:4:36: error: ‘endl’ was not declared in this scope
 std::cout << "Hello, world" << endl;

Either this is a bug in the compiler or in the book. What does the standard say?


I need to clarify a bit. I know that the right answer is to use std::endl. The question was about the text in the book. As Lachlan Easton already said, it is not just a typo. The whole paragraph is (probably) wrong. I can accept this kind of error if the book is by an other (lesser known) author, but I was (and still am) in doubt because it was written by Bjarne.

It's not a bug in the compiler. ADL is used to lookup functions not arguments. operator<< is the function found through ADL here by looking at the parameters std::cout and (what should be) std::endl.

At my code, I do not use int or unsigned int. I only use size_t or ssize_t for portable. For example:

typedef size_t intc;    // (instead of unsigned int)
typedef ssize_t uintc;  // (instead of int)

Because strlen, string, vector... all use size_t, so I usually use size_t. And I only use ssize_t when it may be negative.

But I find that:

The unsigned integer types are ideal for uses that treat storage as a bit array. Using an unsigned instead of an int to gain one more bit to represent positive integers is almost never a good idea. Attempts to ensure that some values are positive by declaring variables unsigned will typically be defeated by the implicit conversion rules.

in the book The C++ Programming Language.

So I am puzzled. Am I wrong? Why does the STL not abide by the suggest on the book?

I'm a practicing C++ programmer (on Unix and gcc 3.x) for the past 6-7 years. I've read Scott Meyer's Effective C++, More Effective C++ and Effective STL cover-to-cover and have lived and practiced his suggestions/techniques along with Boost. I would like to move on to the more advanced aspects of C++ - something along the lines of 'Modern C++ Design' by Andrei Alexandrescu. However, before starting to read this, I am wondering if I should spend time reading Herb Sutter's Exceptional C++ books as well. How would you compare the Effective C++ series with Sutter's books?

Thanks a lot in advance for your response.

Frankly, Herb Sutter yanks a lot in the exception safety ever since the introduction of the idea in one of the journals of the pre-2000 age. The fact he used it a lot on replication and transactional systems makes sense, and unless you are a huge follower and interested in only the software of such 'safety' kind you will be bored to death. Meyers is far more practical and engaging.

Besides, if you want to move on, there are other books in the series, notably from the legends and not the writers for the sake of writing. Look up the bits from Nicolai Josuttis (C++ Templates: The Complete Guide), Aleksey Gurtovoy (C++ Template Metaprogramming) and more recently 'Daddy 2' Stepanov. In my opinion, they are more influential, knowledgable, practical and shaping than anything DDJ or exception safety induced writeups...

And of course, if you ever need to go back to basics (and there is always a reason to), one of the best possible books on the subject is by the daddy himself: The C++ Programming Language (most underestimated and skimmed over book out there).

how can i get C++ documentation, I just came across python's documentation and it was very elaborate. is there anything like that for c++?

I would really suggest reading : The C++ Programming Language: Special Edition by Bjarne Stroustrup since he created the language. The book gives a lot of details on the design decisions that went into the language. It also makes a great reference after you learn the language.

alt text

Amazon link to book

Here is the newest book on Amazon with x11

I am currently reading a c++ book written in 2000 which basically means is using c++ 98.(correct me if i am wrong)

My question is, reading a c++11 book like this one ( which most of the users suggest, requires me to have read already a c++98 book?

C++11 is not a separate language. It's just a new version of the existing one. Reading a C++11 book requires whatever prior knowledge that the C++11 book says it requires.

Bjarne's new version of "The C++ Programming Language" expects no prior knowledge of anything. Some other books will expect prior knowledge.

I found Ivor Horton's Beginning C++ from 1999 in a book shelf, and I was wondering if it's to outdated to be usefull. I allready know some C++, but I'd like to have book as reference. Should I invest in a newer book or was the language pretty similar in 1999?


The 4th edition of the best C++ book has been just published: It contains all the new techniques as well as the new C++11 standard.

It is known that two- and one-dimensional arrays can be used equivalently, by simple coordinate conversion. Is such equivalence guaranteed by the C++ standard, or maybe it's the most convenient way of organizing data, but doesn't have to be obeyed everywhere? For example, is the following code compiler-independent?

std::ofstream ofbStream;"File", std::ios::binary);
char Data[3][5];

for(int i=0; i<3; ++i)
for(int j=0; j<5; ++j)
    Data[i][j] = (char) 5*i+j;

ofbStream.write(&Data[0][0], 15);


The program is expected to write the numbers: 0, 1, 2, ..., 14 to a file.

In his book The C++ Programming Language, Bjarne Stroustrup mentions (C.7.2; p. 838 of the Special Edition, 2000):

... We can initialize ma like this:

void int_ma() {
    for(int i=0; i<3; i++)
        for(int j=0; j<5; j++) ma[i][j] = 10 * i + j; }


The array ma is simply 15 ints that we access as if it were 3 arrays of 5 ints. In particular, there is no single object in memory that is the matrix ma - only the elements are stored. The dimensions 3 and 5 exist in the compiler source only.

(emphasis mine).

In other words, the notation [][]...[] is a compiler construction; syntactical sugar if you will.

For entertainment purposes, I wrote the following code:


int main() {
  double ma[5][3]; double *beg = &ma[0][0]; // case 1
  //double ma[3][5]; double *beg = &ma[0][0]; // case 2
  //double ma[15]; double *beg = &ma[0]; // case 3

  double *end = beg + 15;

  // fill array with random numbers
  std::generate(beg, end, std::rand);

  // display array contents
  std::copy(beg, end, std::ostream_iterator<double>(std::cout, " "));
  return 0;

And compared the assembly generated for the three cases using the compilation command (GCC 4.7.2):

g++ test.cpp -O3 -S -oc1.s 

The cases are called c1.s, c2.s, and c3.s. The output of the command shasum *.s is:

5360e2438aebea682d88277da69c88a3f4af10f3  c1.s
5360e2438aebea682d88277da69c88a3f4af10f3  c2.s
5360e2438aebea682d88277da69c88a3f4af10f3  c3.s

Now, I must mention that the most natural construction seems to be the one-dimensional declaration of ma, that is: double ma[N], because then the initial position is simply ma, and the final position is simply ma + N (this is as opposed to taking the address of the first element of the array).

I find that the algorithms provided by the <algorithm> C++ Standard Library header fit much more snuggly in this case.

Finally, I must encourage you to consider using std::array or std::vector if at all possible.


I'm reading The C++ Programming Language, 4th Edition (by Bjarne Stroustrup) about .

He has the following code example:

void f (const vector<double>& v){
    double d1 = v[1];
    v[2] = 7;


My question is: since v is passed as const how can we change v in second and third statements in the function?

I tried compiling the code and it does not work:

error: assignment of read-only location

So what am I missing here? I doubt it is Bjarne who made a mistake :D


The updated version has the following:

void f(vector<double>& v)
    double d1 = v[1]; // copy the value of the double referred to by v.operator[](1) into d1
    v[2] = 7; // place 7 in the double referred to by the result of v.operator[](2)
    v.push_back(d1); // give push_back() a reference to d1 to wor k with

So it was probably fixed for the next printing.

:::::Binary Tree insertion::::

#include "stdafx.h"
#include <iostream>

using namespace std;

struct TreeNode {
  int value;
  TreeNode* left;
  TreeNode* right;

struct TreeType {
  TreeNode* root;

  void insert(TreeNode* tree, int item);

  void insertItem(int value) {
    insert(root, value);

void TreeType::insert(TreeNode* tree, int number) {
  if (tree == NULL) {
    tree = new TreeNode;
    tree->left = NULL;
    tree->right = NULL;
    tree->value = number;
    cout << "DONE";
  } else if (number < tree->value) {
    insert(tree->left, number);
  } else {
    insert(tree->right, number);

int main() {
  TreeType* MyTree = new TreeType;

  return 0;

I am currently learning Data structures in C++ and this is the code that make insertion in binary trees.

After it is compiled, everything looks fine, however when i try to execute this program, it crashed.

Can anybody tell me where I am wrong?

In your tree constructor, you need to initialize the root pointer to NULL. It's not guaranteed to be initialized as NULL.

When you compile in linux, you can use gdb to show where the source of the segfault is coming from.

Some other notes:

  1. You should assign the value back to root after you've allocated the new node. You're not doing that because you're missing one of the fundamentals of c++. That is, it's based on c. And the thing about c is that is strictly a "by-value" function/method calling paradigm. So all parameters in a function call are by value. When you pass in the memory address for root, you're actually copying the value of the pointer. Then, you're only updating the local value. You need to assign it back to root. If you'd like to learn that concept front to back, I highly recommend watching Jerry Cain's Programming Paradigms course at Stanford.
  2. In your main function, you should try to keep the symbol names as lower_case instead of CamelCase. This helps differentiate variables from types (types should stay CamelCase).
  3. In your TreeType::insert method, you should call the variable tree_node instead of tree. Doing so helps reflect the correct type and avoids confusion.
  4. Whenever possible, try you use the this->root and this->insert notation. Not only will it correctly resolve if you accidentally create a locally scoped root variable, but it's also clearer to the reader where the data or method is defined. Great coding is about communication. It may only take 100-500ms less for the reader to understand where the symbol points to; however, the tiny savings that you can accumulate in avoiding ambiguities add up into a much clearer piece of software. Your future self (and your colleagues) will thank you. See

Lastly, I can overstate enough how important learning from the source is. If you're learning c or c++ for the first time, read and It will save you hours, upon hours, upon hours. After having learned from the source, programming is also A LOT more enjoyable because you understand a good portion of the concepts. And, the truth is, things are more fun when you have a decent level of competence in them.

Is there a function in the Standard Library / Boost that will check whether a cast will result in overflow/underflow of the target type? For example:

unsigned value = static_cast<unsigned>(12.3); // this should pass (lossy but no overflow)
unsigned value = static_cast<unsigned>(1E123); // this should fail
unsigned value = static_cast<unsigned>(-2); // this should also fail

Does somethign like this exist? For the above examples the feature might have functionality similar to this:

template <typename Source, typename Target>
bool checkNoOverflow(const Source value)
  return value >= std::numeric_limits<Target>::lowest() && value <= std::numeric_limits<Target>::max();

The above is just a simplified example, which would fail on corner-cases such as this:

unsigned value = static_cast<unsigned>(-0.1); // valid, result is 0

To be clear, I'm not asking about how to write a function that would work for all cases, but rather I'm after existing functionality in the Standard Library or boost that does this for me.

Unfortunately, no such function exists in the C++ standard library.

If you do have access to Boost, then boost::numeric_cast should do exactly what you want. It will perform a conversion between two numeric types unless the conversion would go outside the range of the target type. In such cases, a boost::numeric::bad_numeric_cast exception is thrown.

If you were curious about implementing your own conversion, you can take a look at The C++ Programming Language 4th Edition by Bjarne Stroustrup (ISBN 978-0321563842).

In Chapter 11.5, he defines a narrow_cast as such:

template<class Target, class Source>
Target narrow_cast(Source v)
   auto r = static_cast<Target>(v); // convert the value to the target type
   if (static_cast<Source>(r)!=v)
      throw runtime_error("narrow_cast<>() failed");
   return r;

This implementation is quite bare and doesn't go quite as far as Boost's does, but could conceivably be modified to suit your needs.

Is there any books which covers the latest standard of c++ ,I want to know much about this standards to use.I want to read a book like the book --> C a reference manual by sir Harbison .

Stroustrup is publishing 4th edition of C++ Programming Language in early 2013. You can preorder it now on amazon. Along with all other stuff, it will include a comprehensive reference to C++ 11 features.

Edit: Here's Amazon link

Coming from the world of Java--Sublime and the Linux command line, IDE's, write-and-go on the fly behavior--, C++ and Visual Studio are the two scariest things I've ever encountered in my life.

You have to deal with menus upon menus upon menus and lots of Studio crashing that can actually break Windows.

Is there any simple way to just write a couple C++ files with a text editor and compile them, using Windows or Linux?

QtCreator is a much simpler IDE than Visual Studio, still it's powerful and working on many platforms.
Also, I suggest you to read The C++ Programming Language, it is an excellent book to learn C++, it has been written by Bjarne Stroustrup (original author of C++).

You might want to try a command-line compiler like gcc, clang or Microsofts C/C++ compiler from the command-line nmake. That can be easier to understand than a complicated gui.

If you want to learn C++ then I recommend the book C++ Primer by Stanley Lippman.

I am a fairly capable Ruby scripter/programmer, but have been feeling pressure to branch out into C++. I haven't been able to find any sites along the lines of "C++ for Ruby Programmers". This site exists for Python (which is quite similar, I know). Does anyone know of a guide that can help me translate my Ruby 'thoughts' into C++?

If you want to learn C++, start here. Once you have learned the fundamentals, you should also look into these: Effective C++, More Effective C++, Effective STL, and Exceptional C++

The book The c++ programming language has sections about dynamic_cast that I'm not sure I understand correctly.

The purpose of dynamic_cast is to deal with the case in which the correctness of the conversion cannot be determined by the compiler. In that case, dynamic_cast(p) looks at the object pointed to by p (if any). If that object is of class T or has a unique base class of type T, then dynamic_cast returns a pointer of type T* to that object; otherwise, nullptr is returned. If the value of p is nullptr, dynamic_cast(p) returns nullptr. Note the requirement that the conversion must be to a uniquely identified object. It is possible to construct examples where the conversion fails and nullptr is returned because the object pointed to by p has more than one subobject representing bases of type T.

Does "It is possible to construct examples where the conversion fails and nullptr is returned because the object pointed to by p has more than one subobject representing bases of type T" mean something like this?

class a {
    a() { }

class b : public a {
    b() { }

class z : public a, public b {
    z() { }

void f(z* p) {
    a* x = dynamic_cast<a*>(p); // ambiguous

And another one, this is taken from the book:

class Component : public virtual Storable { /* ... */ };
class Receiver : public Component { /* ... */ };
class Transmitter : public Component { /* ... */ };
class Radio : public Receiver, public Transmitter { /* ... */ };
The ambiguity for a pointer to a Radio object is not in general detectable at compile time. This kind of run-time ambiguity detection is needed only for virtual bases. For ordinary bases, there is always a unique subobject of a given cast (or none) when downcasting (that is, toward a derived class; §22.2). The equivalent ambiguity for virtual bases occurs when upcasting (that is, toward a base), but such ambiguities are caught at compile time.

I totally don't understand this. What does this mean "For ordinary bases, there is always a unique subobject of a given cast"? I understand if the base is not virtual a subobject will be created for each class that derive from it. But in terms of casting, I just caused an ambiguity error with my above example. And "The equivalent ambiguity for virtual bases occurs when upcasting", what does that mean? Can virtual bases be ambiguous? Can anyone explain this clearer?

For ordinary [non-virtual] bases, there is always a unique subobject of a given cast (or none) when downcasting (that is, toward a derived class; §22.2

That's because non-virtual inheritance creates a strict hierarchy of derived classes, where branches don't come together again. An object must be of some most derived class T, down at a leaf node of that tree of classes. Going up, you can't encounter T again, because a class cannot inherit from itself. Thus, with a dynamic cast down to T, you will end up with the object's most derived class. And similarly for any class in the (or each) inheritance chain.

The book The c++ programming language has this code:

class BB_ival_slider : public Ival_slider, protected BBslider {
    // ...

void f(BB_ival_slider* p)
    Ival_slider* pi1 = p;  // OK
    Ival_slider* pi2 = dynamic_cast<Ival_slider*>(p);    // OK
    BBslider* pbb1 = p;    // error: BBslider is a protected base
    BBslider* pbb2 = dynamic_cast<BBslider*>(p);    // OK: pbb2 becomes nullptr

I tried to prove this behavior for better understanding using the following code:

#include <iostream>

class Ival_slider {
    Ival_slider() {
        std::cout << "Ival_slider called" << '\n';

class BBslider {
    BBslider() {
        std::cout << "BBslider called" << '\n';

class BB_ival_slider : public Ival_slider, protected BBslider {
    BB_ival_slider() {
        std::cout << "BB_ival_slider called" << '\n';

int main() {
    BB_ival_slider* p = new BB_ival_slider{};
    Ival_slider* p1 = p;
    Ival_slider* p2 = dynamic_cast<Ival_slider*>(p);
    BBslider* pbb2 = dynamic_cast<BBslider*>(p);
    if (pbb2) {
        std::cout << "true" << '\n';


BBslider* pbb2 = dynamic_cast<BBslider*>(p);

seems not to work as expected.

g++ -std=c++11 -O0 -g3 -Wall -c -fmessage-length=0 -o cast.o "..\\cast.cpp"
..\cast.cpp: In function 'int main()':
..\cast.cpp:29:43: error: 'BBslider' is an inaccessible base of 'BB_ival_slider'
BBslider* pbb2 = dynamic_cast(p);
..\cast.cpp:29:43: error: 'BBslider' is an inaccessible base of 'BB_ival_slider'

I thought dynamic_cast should at least return nullptr. Is the book wrong? I'm using GCC 4.9.2.

dynamic_cast here is no different from static_cast, and the compiler found that the user code is trying to access a protected base, which is illegal. dynamic_cast does not hide or postpone any compile-time error. If a cast can be determined illegal at compile-time, the compiler will never generate any code and rely on you to check that the cast is actually incorrect at run-time.

I am currently learning about exceptions handling, and here is part of my code:


#include "vector.h"

Vector::Vector(int s)
    if (s < 0) throw length_error{};
    elem = new double[s];
    sz = s;

here is the code I am trying to test the exception by:

    Vector v(-27);
catch (length_error)
    cout << "There was a negative size for your vector.\n";
catch (bad_alloc)
    cout << "The memory was not allocated properly.\n";

When I try to run my application, I get the following error:

error C2440: '<function-style-cast>' : cannot convert from 'initializer-list' to 'std::length_error'

Where is the error?

EDIT: The code was copied from C++ Programming Language Book.

According to std::length_error has the two constructors:

explicit length_error( const std::string& what_arg );
explicit length_error( const char* what_arg );

And you are trying to construct with an empty parameters list. You need to pass in a string to the constructor.

My application starts a subprocess program to read video using the QuickTime framework via fork() and pipes. The subprocess goes into a wait loop when it is not busy, i.e. it does usleep until there is input. The subprocess is not a GUI application and it is written in C++.

When opening AVI video coded using the MSVC codec, a second copy of the application icon shows in the dock and bounces. After about 30 seconds in the Activity Monitor I can see that the subprocess changes to "not responding" even though CPU appears to be ~0%. The subprocess is still running and responding; it's just that Activity Monitor says otherwise.

If I look at the state of the subprocess, via gdb attach or check its output; everything looks fine. I can tell the subprocess to close the file and open another one and continue using it at which point the bouncing dock icon disappears and the process is not marked as not responding.

It's as if OSX thinks my subprocess has crashed (?) but I cannot detect an exception.

How can I stop the subprocess showing an icon in the dock, bouncing and being marked as not responding ?

This is how I set up communication with the subprocess:

#include <unistd.h>

#define READ 0
#define WRITE 1

// Start process
pid_t popen2(const char *command, char * const argv[], int *infp, int *outfp)
  int p_stdin[2], p_stdout[2];
  pid_t pid;

  // Set up pipes
  if(pipe(p_stdin) != 0 || pipe(p_stdout) != 0)

  pid = fork();

  if(pid < 0)
  else if(pid == 0)
    // Set up communication via stdin/out
    dup2(p_stdin[READ], READ);
    dup2(p_stdout[WRITE], WRITE);

    execvp(command, argv); // run subprocess


  // Provide pointers to the file descriptors to the caller
  if(infp == NULL)
    *infp = p_stdin[WRITE];

  if(outfp == NULL)
    *outfp = p_stdout[READ];


See this SO question for more discussion of popen2().

Note: this code may or may not be the cause of my problem. As a first step, I would really like to prove what is the cause.

If you're using a compiler that supports c++11, I'd recommend checking out packaged_tasks.

Alternatively, you could also use condition_variables, but I'd try to get it working with packaged tasks first. Condition variables are more of the primitive than the higher-level packaged tasks. Either way, it's a lot easier (and standards compliant) to use these mechanisms than tradition IPC techniques.

That is, of course, if you don't have to have a separate process.

For further information, I'd highly recommend checking out The C++ Programming Language, 4th Edition. It has simple example of a producer/consumer mechanism with a simple vector that may suit you well. If you don't spring for the book, I'm sure you can find similar examples online for using condition_variables, futures or promises.


I'm reading The C++ Programming Language and trying to understand Constants. The book says this is valid:

const int dmv = 17; // dmv is a named constant
constexpr double max1 = 1.4∗square(dmv); // OK if square(17) is a constant expression

But when I do:

constexpr double square(double x)
    return x * x;

int main()
    const double x = 40.0;
    constexpr double result = 1.2 + square(x);

I got two errors:

  1. expression must have a constant value (in x, if I replace it with a value for ex. 12.4 like square(12.4) the error disappears)
  2. function call must have a constant value in a constant expression (in square method call.)

What is the reason of those errors ? What am I missing ?

Prior to C++11, constexpr didn't exist, and compile-time arithmetic was only possible for integer types (more or less).

In that language, it made sense to make const int "variables" truly constant whenever possible, and not so for const double.

C++11 introduces constexpr, so that the special rule for const T variables is no longer necessary, but removing the rule would unnecessarily break existing code. C++11 also introduces compile-time floating-point arithmetic, but because const double variables were never treated as constant expressions before, and there is little benefit in changing that now, you need to explicitly say constexpr.

constexpr double square(double x)
  return x * x;

int main()
  constexpr double x = 40.0;
  constexpr double result = 1.2 + square(x);

In a COM object generally there are two ways of indicating that a function failed (that I'm aware of):

  • return S_OK and have an [out] parameter to give failure info
  • return a failure HRESULT, and use ICreateErrorInfo to set the info.

Currently what I am doing is using the failure-HRESULT method for failures that are "really bad", i.e. my object will be basically inoperable because this function failed. For example, unable to open its configuration file.

Is this correct, or should failure HRESULTs be reserved only for things like dispatch argument type mismatches?

The short version:

In COM you should use HRESULTs (and strive to use ISupportErrorInfo, etc.) for most/all types of error conditions. The HRESULT mechanism should be viewed as a form of exception throwing. If you are familiar with that, consider "Error conditions" as anything for which you would normally throw an exception in a language that supports them. Use custom return values for things for which you would not normally use exceptions.

For example, use a failure HRESULT for invalid parameters, invalid sequence of operations, network failures, database errors, unexpected conditions such as out-of-memory, etc. On the other hand, use custom out parameters for things like 'polling, data is not ready yet', EOF conditions, maybe 'checked data and it doesn't pass validations'. There is plenty of discussions out there discussing what each should be (e.g. Stroustrup's TC++PL). The specifics will heavily depend on your particular object's semantics.

The longer version:

At a fundamental level, the COM HRESULT mechanism is just an error code mechanism which has been standardized by the infrastructure. This is mostly because COM must support a number of features such as inter-process (DCOM) and inter-threaded (Apartments) execution, system managed services (COM+), etc. The infrastructure has a need to know when something has failed, and it has a need to communicate to both sides its own infrastructure-related errors. Everybody needs to agree on how to communicate errors.

Each language and programmer has a choice of how to present or handle those errors. In C++, we typically handle the HRESULTs as error codes (although you can translate them into exceptions if you prefer error handling that way). In .NET languages, failure HRESULTs are translated into exceptions because that's the preferred error mechanism in .NET.

VB6 supports "either". Now, I know VB6's so-called exception handling has a painful syntax and limited scoping options for handlers, but you don't have to use it if you don't want to. You can always use ON ERROR RESUME NEXT and do it by hand if you think the usage pattern justifies it in a specific situation. It's just that instead of writing something like this:

statusCode = obj.DoSomething(param1)
If IS_FAILURE(statusCode) Then
    'handle error
End If

Your write it like this:

obj.DoSomething param1
IF Error.Number <> 0 Then
    'handle error
End If

VB6 is simply hiding the error code return value from the method call (and allowing the object's programmer to substitute it for a "virtual return value" via [retval]).

If you make up your own error reporting mechanism instead of using HRESULTs, you will:

  1. Spend a lot of time reinventing a rich error reporting mechanism that will probably mirror what ISupportsErrorInfo already gives you (or most likely, not provide any rich error information).
  2. Hide the error status from COM's infrastructure (which might or might not matter).
  3. Force your VB6 clients to make one specific choice out of the two options they have: they must do explicit line-by-line check, or more likely just ignore the error condition by mistake, even if they would prefer an error handler.
  4. Force your (say) C# clients to handle your errors in ways that runs contrary to the natural style of the language (to have to check every method call explicitly and... likely throw an exception by hand).

Hello everybody here's a question i am trying to solve

Write a C++ program that allows the user to enter a number and then generate its multiplication table,formatting it into 5 columns and 20 lines. Interaction with the program should look like this(Only the first 4 lines are shown)

 Enter a number 7:

 7   14   21   28   35
 42  49  56  63  70
 77  84  91  98  105

well here is what i tried

#include <iostream>

using namespace std;

int main()
    int n, mul;
    cout << "Enter a number" << endl;
    cin >> n;

    for(int i = 1; i <= 100; i++) {
        mul = n * i;
        cout << mul << "\t";

    return 0;

only the part of 5 columns and 20 lines is left

Loop through each line. Within each line loop through each column. At the end of each line print an EOLN character \n signaling the end of the line. If you are new, get some decent C++ book such as The C++ Programming Language, 4th Edition or read some tutorials.

The setw() function can be use to indicate the width of the "cell" of the table:

cout << setw(n) << mul

This causes the program to ensure the output is at least n in length by adding trailing spaces if the output is not long enough. However, it has no effect if the length of the output is larger than n. To avoid that, n should be the length of the highest mulitple + 1.