How to write C++ getters and setters

There are two distinct forms of “properties” that turn up in the standard library, which I will categorise as “Identity oriented” and “Value oriented”. Which you choose depends on how the system should interact with Foo. Neither is “more correct”. Identity oriented class Foo { X x_; public: X & x() { return x_; } …

Read more

Should I include or in C++ programs?

Consider the following programs: Sample 1: #include<stdio.h> int main() { printf(“Hello World”); return 0; } Sample 2: #include<cstdio> int main() { printf(“Hello World”); return 0; } Both work as expected. So which usage is more appropriate? The answer is: Neither! Surprised? Read on. The C++ Standard library provides all standard C headers for compatibility reason, …

Read more

What happens when an exception goes unhandled in a multithreaded C++11 program?

Nothing has really changed. The wording in n3290 is: If no matching handler is found, the function std::terminate() is called The behavior of terminate can be customized with set_terminate, but: Required behavior: A terminate_handler shall terminate execution of the program without returning to the caller. So the program exits in such a case, other threads …

Read more

What are all the member-functions created by compiler for a class? Does that happen all the time?

C++98/03 If they are needed, the compiler will generate a default constructor for you unless you declare any constructor of your own. the compiler will generate a copy constructor for you unless you declare your own. the compiler will generate a copy assignment operator for you unless you declare your own. the compiler will generate …

Read more

How to get IOStream to perform better?

Here is what I have gathered so far: Buffering: If by default the buffer is very small, increasing the buffer size can definitely improve the performance: it reduces the number of HDD hits it reduces the number of system calls Buffer can be set by accessing the underlying streambuf implementation. char Buffer[N]; std::ifstream file(“file.txt”); file.rdbuf()->pubsetbuf(Buffer, …

Read more

Why do we actually need Private or Protected inheritance in C++?

It is useful when you want to have access to some members of the base class, but without exposing them in your class interface. Private inheritance can also be seen as some kind of composition: the C++ faq-lite gives the following example to illustrate this statement class Engine { public: Engine(int numCylinders); void start(); // …

Read more

shared_from_this causing bad_weak_ptr

John Zwinck’s essential analysis is spot on: The bug is that you’re using shared_from_this() on an object which has no shared_ptr pointing to it. This violates a precondition of shared_from_this(), namely that at least one shared_ptr must already have been created (and still exist) pointing to this. However, his advice seems completely beside the point …

Read more