C++ interview questions
23 questions with answers. 1,338 open jobs in India ask for C++.
What is the '-->' operator in C/C++?
-->is not an operator. It is in fact two separate operators,--and>.The code in the condition decrements
x, while returningx's original (not decremented) value, and then compares the original value with0using the>operator.To better understand, the statement could be written as follows:
while( (x--) > 0 )From Stack Overflow: asked by GManNickG, answered by Charles Salvia (CC BY-SA 4.0)
What are the differences between a pointer variable and a reference variable?
A pointer can be re-assigned:
int x = 5; int y = 6; int *p; p = &x; p = &y; *p = 10; assert(x == 5); assert(y == 10);A reference cannot be re-bound, and must be bound at initialization:
int x = 5; int y = 6; int &q; // error int &r = x;A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary
&operator and a certain amount of space that can be measured with thesizeofoperator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable.int x = 0; int &r = x; int *p = &x; int *p2 = &r; assert(p == p2); // &x == &r assert(&p != &p2);It is possible to create a pointer to a pointer, but not a pointer to a reference.
int **pp; // OK, pointer to pointer int &*pr; // ill-formed, pointer to referenceIt is possible to create an array of pointers, but not an array of references.
int *ap[]; // OK, array of pointers int &ar[]; // ill-formed, array of referencesYou can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection because references to references collapse.
int x = 0; int y = 0; int *p = &x; int *q = &y; int **pp = &p; **pp = 2; pp = &q; // *pp is now q **pp = 4; assert(y == 4); assert(x == 2);A pointer can be assigned
nullptr, whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference tonullptr, but this is undefined and will not behave consistently./* the code below is undefined; your compiler may optimise it * differently, emit warnings, or outright refuse to compile it */ int &r = *static_cast<int *>(nullptr); // prints "null" under GCC 10 std::cout << (&r != nullptr ? "not null" : "null") << std::endl; bool f(int &r) { return &r != nullptr; } // prints "not null" under GCC 10 std::cout << (f(*static_cast<int *>(nullptr)) ? "not null" : "null") << std::endl;You can, however, have a reference to a pointer whose value is
nullptr.Pointers are ContiguousIterators (of an array). You can use
++to go to the next item that a pointer is pointing to, and+ 4to go to the 5th element.A pointer needs to be dereferenced with
*to access the object it points to, whereas a reference can be used directly. A pointer to a class/struct uses->to access its members whereas a reference uses a..Const references and rvalue references can be bound to temporaries (see temporary materialization). Pointers cannot (not without some indirection):
const int &x = int(12); // legal C++ int *y = &int(12); // illegal to take the address of a temporary.This makes
const &more convenient to use in argument lists and so forth.
From Stack Overflow: asked by prakash, answered by Brian R. Bondy (CC BY-SA 4.0)
What does the explicit keyword mean?
The compiler is allowed to make one implicit conversion to resolve the parameters to a function. This means that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.
Here's an example with converting constructors that shows how it works:
struct Foo { // Single parameter constructor, can be used as an implicit conversion. // Such a constructor is called "converting constructor". Foo(int x) {} }; struct Faz { // Also a converting constructor. Faz(Foo foo) {} }; // The parameter is of type Foo, not of type int, so it looks like // we have to pass a Foo. void bar(Foo foo) {}; int main() { // However, the converting constructor allows us to pass an int. bar(42); // Also allowed thanks to the converting constructor. Foo foo = 42; // Error! This would require two conversions (int -> Foo -> Faz). Faz faz = 42; }Prefixing the
explicitkeyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function callbar(42). It is now necessary to call for conversion explicitly withbar(Foo(42))The reason you might want to do this is to avoid accidental construction that can hide bugs.
Contrived example:- You have a
MyStringclass with a constructor that constructs a string of the given size. You have a functionprint(const MyString&)(as well as an overloadprint (char *string)), and you callprint(3)(when you actually intended to callprint("3")). You expect it to print "3", but it prints an empty string of length 3 instead.
From Stack Overflow: asked by Skizz, answered by Skizz (CC BY-SA 4.0)
- You have a
What's the problem with "using namespace std;"?
Consider two libraries called Foo and Bar:
using namespace foo; using namespace bar;Everything works fine, and you can call
Blah()from Foo andQuux()from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function calledQuux(). Now you've got a conflict: Both Foo 2.0 and Bar importQuux()into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match.If you had used
foo::Blah()andbar::Quux(), then the introduction offoo::Quux()would have been a non-event.From Stack Overflow: asked by akbiggs, answered by Greg Hewgill (CC BY-SA 4.0)
When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used?
static_caststatic_castis the first cast you should attempt to use. It does things like implicit conversions between types (such asinttofloat, or pointer tovoid*), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly statingstatic_castisn't necessary, but it's important to note that theT(something)syntax is equivalent to(T)somethingand should be avoided (more on that later). AT(something, something_else)is safe, however, and guaranteed to call the constructor.static_castcan also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn't cast throughvirtualinheritance. It does not do checking, however, and it is undefined behavior tostatic_castdown a hierarchy to a type that isn't actually the type of the object.const_castconst_castcan be used to remove or addconstto a variable; no other C++ cast is capable of removing it (not evenreinterpret_cast). It is important to note that modifying a formerlyconstvalue is only undefined if the original variable isconst; if you use it to take theconstoff a reference to something that wasn't declared withconst, it is safe. This can be useful when overloading member functions based onconst, for instance. It can also be used to addconstto an object, such as to call a member function overload.const_castalso works similarly onvolatile, though that's less common.dynamic_castdynamic_castis exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. Thedynamic_castwill seek out the desired object and return it if possible. If it can't, it will returnnullptrin the case of a pointer, or throwstd::bad_castin the case of a reference.dynamic_casthas some limitations, though. It doesn't work if there are multiple objects of the same type in the inheritance hierarchy (the so-called 'dreaded diamond') and you aren't usingvirtualinheritance. It also can only go through public inheritance - it will always fail to travel throughprotectedorprivateinheritance. This is rarely an issue, however, as such forms of inheritance are rare.reinterpret_castreinterpret_castis the most dangerous cast, and should be used very sparingly. It turns one type directly into another — such as casting the value from one pointer to another, or storing a pointer in anint, or all sorts of other nasty things. Largely, the only guarantee you get withreinterpret_castis that normally if you cast the result back to the original type, you will get the exact same value (but not if the intermediate type is smaller than the original type). There are a number of conversions thatreinterpret_castcannot do, too. It's often abused for particularly weird conversions and bit manipulations, like turning a raw data stream into actual data, or storing data in the low bits of a pointer to aligned data. For those cases, seestd::bit_cast.C-Style Cast and Function-Style Cast
C-style cast and function-style cast are casts using
(type)objectortype(object), respectively, and are functionally equivalent. They are defined as the first of the following which succeeds:const_caststatic_cast(though ignoring access restrictions)static_cast(see above), thenconst_castreinterpret_castreinterpret_cast, thenconst_cast
Read the rest at the sourceFrom Stack Overflow: asked by James Eichele, answered by coppro (CC BY-SA 4.0)
What is the difference between #include <filename> and #include "filename"?
What differs is the locations in which the preprocessor searches for the file to be included.
#include <filename>The preprocessor searches in an implementation-defined manner, normally in directories pre-designated by the compiler/IDE. This method is normally used to include header files for the C standard library and other header files associated with the target platform.#include "filename"The preprocessor also searches in an implementation-defined manner, but one that is normally used to include programmer-defined header files and typically includes same directory as the file containing the directive (unless an absolute path is given).
For GCC, a more complete description is available in the GCC documentation on search paths.
From Stack Overflow: asked by quest49, answered by quest49 (CC BY-SA 4.0)
What is The Rule of Three?
Introduction
C++ treats variables of user-defined types with value semantics. This means that objects are implicitly copied in various contexts, and we should understand what "copying an object" actually means.
Let us consider a simple example:
class person { std::string name; int age; public: person(const std::string& name, int age) : name(name), age(age) { } }; int main() { person a("Bjarne Stroustrup", 60); person b(a); // What happens here? b = a; // And here? }(If you are puzzled by the
name(name), age(age)part, this is called a member initializer list.)Special member functions
What does it mean to copy a
personobject? Themainfunction shows two distinct copying scenarios. The initializationperson b(a);is performed by the copy constructor. Its job is to construct a fresh object based on the state of an existing object. The assignmentb = ais performed by the copy assignment operator. Its job is generally a little more complicated because the target object is already in some valid state that needs to be dealt with.Since we declared neither the copy constructor nor the assignment operator (nor the destructor) ourselves, these are implicitly defined for us. Quote from the standard:
The [...] copy constructor and copy assignment operator, [...] and destructor are special member functions. [ Note: The implementation will implicitly declare these member functions for some class types when the program does not explicitly declare them. The implementation will implicitly define them if they are used. [...] end note ] [n3126.pdf section 12 §1]
By default, copying an object means copying its members:
The implicitly-defined copy constructor for a non-union class X performs a memberwise copy of its subobjects. [n3126.pdf section 12.8 §16]
The implicitly-defined copy assignment operator for a non-union class X performs memberwise copy assignment of its subobjects. [n3126.pdf section 12.8 §30]
Implicit definitions
The implicitly-defined special member functions for
personlook like this:// 1. copy constructor person(const person& that) : name(that.name), age(that.age) { } // 2. copy assignment operator person& operator=(const person& that) { name = that.name; age = that.age; return *this; } // 3. destructor ~person() { }Memberwise copying is exactly what we want in this case:
nameandageare copied, so we get a self-contained, independentpersonobject. The implicitly-defined destructor is always empty. This is also fine in this case since we did not acquire any resources in the constructor. The members' destructors are implicitly called after thepersondestructor is finished:After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X's direct [...] members [n3126.pdf 12.4 §6]
Managing resources
So when should we declare those special member functions explicitly? When our class manages a resource, that is, when an object of the class is responsible for that resource. That usually means the resource is acquired in the constructor (or passed into the constructor) and released in the destructor.
Let us go back in time to pre-standard C++. There was no such thing as
std::string, and programmers were in love with pointers. Thepersonclass might have looked like this:Read the rest at the sourceFrom Stack Overflow: asked by fredoverflow, answered by fredoverflow (CC BY-SA 4.0)
What are the basic rules and idioms for operator overloading?
Common Operators to Overload
Most of the work in overloading operators is boilerplate code. That is little wonder, since operators are merely syntactic sugar. Their actual work could be done by (and often is forwarded to) plain functions. But it is important that you get this boilerplate code right. If you fail, either your operator’s code won’t compile, your users’ code won’t compile, or your users’ code will behave surprisingly.
Assignment Operator
There's a lot to be said about assignment. However, most of it has already been said in GMan's famous Copy-And-Swap FAQ, so I'll skip most of it here, only listing the perfect assignment operator for reference:
X& X::operator=(X rhs) { swap(rhs); return *this; }Stream Insertion and Extraction
Disclaimer For overloading <<and>>as bitwise shift operators, skip to the section Binary Arithmetic Operators.The bitwise shift operators
<<and>>, although still used in hardware interfacing for the bit-manipulation functions they inherit from C, have become more prevalent as overloaded stream input and output operators in most applications.The stream operators, among the most commonly overloaded operators, are binary infix operators for which the syntax does not specify any restriction on whether they should be members or non-members. However, their left operands are streams from the standard library, and you cannot add member functions to those1, so you need to implement these operators for your own types as non-member functions2. The canonical forms of the two are these:
std::ostream& operator<<(std::ostream& os, const T& obj) { // Write obj to stream return os; } std::istream& operator>>(std::istream& is, T& obj) { // Read obj from stream if( /* no valid object of T found in stream */ ) is.setstate(std::ios::failbit); return is; }When implementing
operator>>, manually setting the stream’s state is only necessary when the reading itself succeeded, but the result is not what would be expected.1 Note that some of the
<<overloads of the standard library are implemented as member functions, and some as free functions. Only the locale-dependent functions are member functions, such asoperator<<(long).2 According to the rules of thumb, the insertion/extraction operators should be member functions because they modify the left operand. However, we cannot follow the rules of thumb here.
Function Call Operator
The function call operator, used to create function objects, also known as functors, must be defined as a member function, so it always has the implicit
thisargument of member functions. Other than this, it can be overloaded to take any number of additional arguments, including zero.Here's an example of the syntax:
struct X { // Overloaded call operator int operator()(const std::string& y) { return /* ... */; } };Usage:
X f; int a = f("hello");Throughout the C++ standard library, function objects are always copied. Your own function objects should therefore be cheap to copy. If a function object absolutely needs to use data which is expensive to copy, it is better to store that data elsewhere and have the function object refer to it.
Comparison Operators
Read the rest at the sourceFrom Stack Overflow: asked by sbi, answered by sbi (CC BY-SA 4.0)
Why are elementwise additions much faster in separate loops than in a combined loop?
Upon further analysis of this, I believe this is (at least partially) caused by the data alignment of the four-pointers. This will cause some level of cache bank/way conflicts.
If I've guessed correctly on how you are allocating your arrays, they are likely to be aligned to the page line.
This means that all your accesses in each loop will fall on the same cache way. However, Intel processors have had 8-way L1 cache associativity for a while. But in reality, the performance isn't completely uniform. Accessing 4-ways is still slower than say 2-ways.
EDIT: It does in fact look like you are allocating all the arrays separately. Usually when such large allocations are requested, the allocator will request fresh pages from the OS. Therefore, there is a high chance that large allocations will appear at the same offset from a page-boundary.
Here's the test code:
int main(){ const int n = 100000; #ifdef ALLOCATE_SEPERATE double *a1 = (double*)malloc(n * sizeof(double)); double *b1 = (double*)malloc(n * sizeof(double)); double *c1 = (double*)malloc(n * sizeof(double)); double *d1 = (double*)malloc(n * sizeof(double)); #else double *a1 = (double*)malloc(n * sizeof(double) * 4); double *b1 = a1 + n; double *c1 = b1 + n; double *d1 = c1 + n; #endif // Zero the data to prevent any chance of denormals. memset(a1,0,n * sizeof(double)); memset(b1,0,n * sizeof(double)); memset(c1,0,n * sizeof(double)); memset(d1,0,n * sizeof(double)); // Print the addresses cout << a1 << endl; cout << b1 << endl; cout << c1 << endl; cout << d1 << endl; clock_t start = clock(); int c = 0; while (c++ < 10000){ #if ONE_LOOP for(int j=0;j<n;j++){ a1[j] += b1[j]; c1[j] += d1[j]; } #else for(int j=0;j<n;j++){ a1[j] += b1[j]; } for(int j=0;j<n;j++){ c1[j] += d1[j]; } #endif } clock_t end = clock(); cout << "seconds = " << (double)(end - start) / CLOCKS_PER_SEC << endl; system("pause"); return 0; }Benchmark Results:
EDIT: Results on an actual Core 2 architecture machine:
2 x Intel Xeon X5482 Harpertown @ 3.2 GHz:
#define ALLOCATE_SEPERATE #define ONE_LOOP 00600020 006D0020 007A0020 00870020 seconds = 6.206 #define ALLOCATE_SEPERATE //#define ONE_LOOP 005E0020 006B0020 00780020 00850020 seconds = 2.116 //#define ALLOCATE_SEPERATE #define ONE_LOOP 00570020 00633520 006F6A20 007B9F20 seconds = 1.894 //#define ALLOCATE_SEPERATE //#define ONE_LOOP 008C0020 00983520 00A46A20 00B09F20 seconds = 1.993Observations:
6.206 seconds with one loop and 2.116 seconds with two loops. This reproduces the OP's results exactly.
In the first two tests, the arrays are allocated separately. You'll notice that they all have the same alignment relative to the page.
In the second two tests, the arrays are packed together to break that alignment. Here you'll notice both loops are faster. Furthermore, the second (double) loop is now the slower one as you would normally expect.
As @Stephen Cannon points out in the comments, there is a very likely possibility that this alignment causes false aliasing in the load/store units or the cache. I Googled around for this and found that Intel actually has a hardware counter for partial address aliasing stalls:
5 Regions - Explanations
Region 1:
This one is easy. The dataset is so small that the performance is dominated by overhead like looping and branching.
Region 2:
Read the rest at the sourceFrom Stack Overflow: asked by Johannes Gerer, answered by Mysticial (CC BY-SA 4.0)
What is the copy-and-swap idiom?
Overview
Why do we need the copy-and-swap idiom?
Any class that manages a resource (a wrapper, like a smart pointer) needs to implement The Big Three. While the goals and implementation of the copy-constructor and destructor are straightforward, the copy-assignment operator is arguably the most nuanced and difficult. How should it be done? What pitfalls need to be avoided?
The copy-and-swap idiom is the solution, and elegantly assists the assignment operator in achieving two things: avoiding code duplication, and providing a strong exception guarantee.
How does it work?
Conceptually, it works by using the copy-constructor's functionality to create a local copy of the data, then takes the copied data with a
swapfunction, swapping the old data with the new data. The temporary copy then destructs, taking the old data with it. We are left with a copy of the new data.In order to use the copy-and-swap idiom, we need three things: a working copy-constructor, a working destructor (both are the basis of any wrapper, so should be complete anyway), and a
swapfunction.A swap function is a non-throwing function that swaps two objects of a class, member for member. We might be tempted to use
std::swapinstead of providing our own, but this would be impossible;std::swapuses the copy-constructor and copy-assignment operator within its implementation, and we'd ultimately be trying to define the assignment operator in terms of itself!(Not only that, but unqualified calls to
swapwill use our custom swap operator, skipping over the unnecessary construction and destruction of our class thatstd::swapwould entail.)An in-depth explanation
The goal
Let's consider a concrete case. We want to manage, in an otherwise useless class, a dynamic array. We start with a working constructor, copy-constructor, and destructor:
#include <algorithm> // std::copy #include <cstddef> // std::size_t class dumb_array { public: // (default) constructor dumb_array(std::size_t size = 0) : mSize(size), mArray(mSize ? new int[mSize]() : nullptr) { } // copy-constructor dumb_array(const dumb_array& other) : mSize(other.mSize), mArray(mSize ? new int[mSize] : nullptr) { // note that this is non-throwing, because of the data // types being used; more attention to detail with regards // to exceptions must be given in a more general case, however std::copy(other.mArray, other.mArray + mSize, mArray); } // destructor ~dumb_array() { delete [] mArray; } private: std::size_t mSize; int* mArray; };This class almost manages the array successfully, but it needs
operator=to work correctly.A failed solution
Here's how a naive implementation might look:
// the hard part dumb_array& operator=(const dumb_array& other) { if (this != &other) // (1) { // get rid of the old data... delete [] mArray; // (2) mArray = nullptr; // (2) *(see footnote for rationale) // ...and put in the new mSize = other.mSize; // (3) mArray = mSize ? new int[mSize] : nullptr; // (3) std::copy(other.mArray, other.mArray + mSize, mArray); // (3) } return *this; }And we say we're finished; this now manages an array, without leaks. However, it suffers from three problems, marked sequentially in the code as
(n).Read the rest at the sourceFrom Stack Overflow: asked by GManNickG, answered by GManNickG (CC BY-SA 4.0)
Why can templates only be implemented in the header file?
Caveat: It is not necessary to put the implementation in the header file, see the alternative solution at the end of this answer.
Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:
template<typename T> struct Foo { T bar; void doSomething(T param) {/* do stuff using T */} }; // somewhere in a .cpp Foo<int> f;When reading this line, the compiler will create a new class (let's call it
FooInt), which is equivalent to the following:struct FooInt { int bar; void doSomething(int param) {/* do stuff using int */} };Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case
int). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.
Foo.h
template <typename T> struct Foo { void doSomething(T param); }; #include "Foo.tpp"Foo.tpp
template <typename T> void Foo<T>::doSomething(T param) { //implementation }This way, implementation is still separated from declaration, but is accessible to the compiler.
Alternative solution
Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:
Foo.h
// no implementation template <typename T> struct Foo { ... };Foo.cpp
// implementation of Foo's methods // explicit instantiations template class Foo<int>; template class Foo<float>; // You will only be able to use Foo with int or floatIf my explanation isn't clear enough, you can have a look at the C++ Super-FAQ on this subject.
From Stack Overflow: asked by MainID, answered by Luc Touraille (CC BY-SA 4.0)
Why is reading lines from stdin much slower in C++ than Python?
tl;dr: Because of different default settings in C++ requiring more system calls.
By default,
cinis synchronized with stdio, which causes it to avoid any input buffering. If you add this to the top of your main, you should see much better performance:std::ios_base::sync_with_stdio(false);Normally, when an input stream is buffered, instead of reading one character at a time, the stream will be read in larger chunks. This reduces the number of system calls, which are typically relatively expensive. However, since the
FILE*basedstdioandiostreamsoften have separate implementations and therefore separate buffers, this could lead to a problem if both were used together. For example:int myvalue1; cin >> myvalue1; int myvalue2; scanf("%d",&myvalue2);If more input was read by
cinthan it actually needed, then the second integer value wouldn't be available for thescanffunction, which has its own independent buffer. This would lead to unexpected results.To avoid this, by default, streams are synchronized with
stdio. One common way to achieve this is to havecinread each character one at a time as needed usingstdiofunctions. Unfortunately, this introduces a lot of overhead. For small amounts of input, this isn't a big problem, but when you are reading millions of lines, the performance penalty is significant.Fortunately, the library designers decided that you should also be able to disable this feature to get improved performance if you knew what you were doing, so they provided the
sync_with_stdiomethod. From this link (emphasis added):If the synchronization is turned off, the C++ standard streams are allowed to buffer their I/O independently, which may be considerably faster in some cases.
From Stack Overflow: asked by JJC, answered by Vaughn Cato (CC BY-SA 4.0)
What is a smart pointer and when should I use one?
UPDATE
This answer is rather old, and so describes what was 'good' at the time, which was smart pointers provided by the Boost library. Since C++11, the standard library has provided sufficient smart pointers types, and so you should favour the use of
std::unique_ptr,std::shared_ptrandstd::weak_ptr.There was also
std::auto_ptr. It was very much like a scoped pointer, except that it also had the "special" dangerous ability to be copied — which also unexpectedly transfers ownership.
It was deprecated in C++11 and removed in C++17, so you shouldn't use it.std::auto_ptr<MyObject> p1 (new MyObject()); std::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership. // p1 gets set to empty! p2->DoSomething(); // Works. p1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception.OLD ANSWER
A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way.
Smart pointers should be preferred over raw pointers. If you feel you need to use pointers (first consider if you really do), you would normally want to use a smart pointer as this can alleviate many of the problems with raw pointers, mainly forgetting to delete the object and leaking memory.
With raw pointers, the programmer has to explicitly destroy the object when it is no longer useful.
// Need to create the object to achieve some goal MyObject* ptr = new MyObject(); ptr->DoSomething(); // Use the object in some way delete ptr; // Destroy the object. Done with it. // Wait, what if DoSomething() raises an exception...?A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it.
SomeSmartPtr<MyObject> ptr(new MyObject()); ptr->DoSomething(); // Use the object in some way. // Destruction of the object happens, depending // on the policy the smart pointer class uses. // Destruction would happen even if DoSomething() // raises an exceptionThe simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by
boost::scoped_ptrorstd::unique_ptr.void f() { { std::unique_ptr<MyObject> ptr(new MyObject()); ptr->DoSomethingUseful(); } // ptr goes out of scope -- // the MyObject is automatically destroyed. // ptr->Oops(); // Compile error: "ptr" not defined // since it is no longer in scope. }Note that
std::unique_ptrinstances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call.std::unique_ptrs are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed.Read the rest at the sourceFrom Stack Overflow: asked by Alex Reynolds, answered by Lloyd (CC BY-SA 4.0)
What is the effect of `extern "C"` in C++?
extern "C"makes a function-name in C++ have C linkage (compiler does not mangle the name) so that client C code can link to (use) your function using a C compatible header file that contains just the declaration of your function. Your function definition is contained in a binary format (that was compiled by your C++ compiler) that the client C linker will then link to using the C name.Since C++ has overloading of function names and C does not, the C++ compiler cannot just use the function name as a unique id to link to, so it mangles the name by adding information about the arguments. A C compiler does not need to mangle the name since you can not overload function names in C. When you state that a function has
extern "C"linkage in C++, the C++ compiler does not add argument/parameter type information to the name used for linkage.Just so you know, you can specify
extern "C"linkage to each individual declaration/definition explicitly or use a block to group a sequence of declarations/definitions to have a certain linkage:extern "C" void foo(int); extern "C" { void g(char); int i; }If you care about the technicalities, they are listed in section 7.5 of the C++03 standard, here is a brief summary (with emphasis on
extern "C"):extern "C"is a linkage-specification- Every compiler is required to provide "C" linkage
- A linkage specification shall occur only in namespace scope
- All function types, function names and variable names have a language linkage See Richard's Comment: Only function names and variable names with external linkage have a language linkage
- Two function types with distinct language linkages are distinct types even if otherwise identical
- Linkage specs nest, inner one determines the final linkage
extern "C"is ignored for class members- At most one function with a particular name can have "C" linkage (regardless of namespace)
extern "C"forces a function to have external linkage (cannot make it static) See Richard's comment:staticinsideextern "C"is valid; an entity so declared has internal linkage, and so does not have a language linkage- Linkage from C++ to objects defined in other languages and to objects defined in C++ from other languages is implementation-defined and language-dependent. Only where the object layout strategies of two language implementations are similar enough can such linkage be achieved
From Stack Overflow: asked by Litherum, answered by Faisal Vali (CC BY-SA 4.0)
What is move semantics?
I find it easiest to understand move semantics with example code. Let's start with a very simple string class which only holds a pointer to a heap-allocated block of memory:
#include <cstring> #include <algorithm> class string { char* data; public: string(const char* p) { size_t size = std::strlen(p) + 1; data = new char[size]; std::memcpy(data, p, size); }Since we chose to manage the memory ourselves, we need to follow the rule of three. I am going to defer writing the assignment operator and only implement the destructor and the copy constructor for now:
~string() { delete[] data; } string(const string& that) { size_t size = std::strlen(that.data) + 1; data = new char[size]; std::memcpy(data, that.data, size); }The copy constructor defines what it means to copy string objects. The parameter
const string& thatbinds to all expressions of type string which allows you to make copies in the following examples:string a(x); // Line 1 string b(x + y); // Line 2 string c(some_function_returning_a_string()); // Line 3Now comes the key insight into move semantics. Note that only in the first line where we copy
xis this deep copy really necessary, because we might want to inspectxlater and would be very surprised ifxhad changed somehow. Did you notice how I just saidxthree times (four times if you include this sentence) and meant the exact same object every time? We call expressions such asx"lvalues".The arguments in lines 2 and 3 are not lvalues, but rvalues, because the underlying string objects have no names, so the client has no way to inspect them again at a later point in time. rvalues denote temporary objects which are destroyed at the next semicolon (to be more precise: at the end of the full-expression that lexically contains the rvalue). This is important because during the initialization of
bandc, we could do whatever we wanted with the source string, and the client couldn't tell a difference!C++0x introduces a new mechanism called "rvalue reference" which, among other things, allows us to detect rvalue arguments via function overloading. All we have to do is write a constructor with an rvalue reference parameter. Inside that constructor we can do anything we want with the source, as long as we leave it in some valid state:
string(string&& that) // string&& is an rvalue reference to a string { data = that.data; that.data = nullptr; }What have we done here? Instead of deeply copying the heap data, we have just copied the pointer and then set the original pointer to null (to prevent 'delete[]' from source object's destructor from releasing our 'just stolen data'). In effect, we have "stolen" the data that originally belonged to the source string. Again, the key insight is that under no circumstance could the client detect that the source had been modified. Since we don't really do a copy here, we call this constructor a "move constructor". Its job is to move resources from one object to another instead of copying them.
Congratulations, you now understand the basics of move semantics! Let's continue by implementing the assignment operator. If you're unfamiliar with the copy and swap idiom, learn it and come back, because it's an awesome C++ idiom related to exception safety.
string& operator=(string that) { std::swap(data, that.data); return *this; } };Huh, that's it? "Where's the rvalue reference?" you might ask. "We don't need it here!" is my answer :)
Read the rest at the sourceFrom Stack Overflow: asked by dicroce, answered by fredoverflow (CC BY-SA 4.0)
When to use virtual destructors?
Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:
class Base { // some virtual methods }; class Derived : public Base { ~Derived() { // Do some important cleanup } };Here, you'll notice that I didn't declare Base's destructor to be
virtual. Now, let's have a look at the following snippet:Base *b = new Derived(); // use b delete b; // Here's the problem!Since Base's destructor is not
virtualandbis aBase*pointing to aDerivedobject,delete bhas undefined behaviour:[In
delete b], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.
To sum up, always make base classes' destructors
virtualwhen they're meant to be manipulated polymorphically.If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call
deleteon a base class pointer.You can learn more about virtuality and virtual base class destructor in this article from Herb Sutter.
From Stack Overflow: asked by Lodle, answered by Luc Touraille (CC BY-SA 4.0)
Why should I use a pointer rather than the object itself?
It's very unfortunate that you see dynamic allocation so often. That just shows how many bad C++ programmers there are.
In a sense, you have two questions bundled up into one. The first is when should we use dynamic allocation (using
new)? The second is when should we use pointers?The important take-home message is that you should always use the appropriate tool for the job. In almost all situations, there is something more appropriate and safer than performing manual dynamic allocation and/or using raw pointers.
Dynamic allocation
In your question, you've demonstrated two ways of creating an object. The main difference is the storage duration of the object. When doing
Object myObject;within a block, the object is created with automatic storage duration, which means it will be destroyed automatically when it goes out of scope. When you donew Object(), the object has dynamic storage duration, which means it stays alive until you explicitlydeleteit. You should only use dynamic storage duration when you need it. That is, you should always prefer creating objects with automatic storage duration when you can.The main two situations in which you might require dynamic allocation:
- You need the object to outlive the current scope - that specific object at that specific memory location, not a copy of it. If you're okay with copying/moving the object (most of the time you should be), you should prefer an automatic object.
- You need to allocate a lot of memory, which may easily fill up the stack. It would be nice if we didn't have to concern ourselves with this (most of the time you shouldn't have to), as it's really outside the purview of C++, but unfortunately, we have to deal with the reality of the systems we're developing for.
When you do absolutely require dynamic allocation, you should encapsulate it in a smart pointer or some other type that performs RAII (like the standard containers). Smart pointers provide ownership semantics of dynamically allocated objects. Take a look at
std::unique_ptrandstd::shared_ptr, for example. If you use them appropriately, you can almost entirely avoid performing your own memory management (see the Rule of Zero).Pointers
However, there are other more general uses for raw pointers beyond dynamic allocation, but most have alternatives that you should prefer. As before, always prefer the alternatives unless you really need pointers.
Read the rest at the sourceFrom Stack Overflow: asked by Krystian Dobkowski, answered by Joseph Mansfield (CC BY-SA 4.0)
What is the difference between const int*, const int * const, and int * const?
Read it backwards (as driven by Clockwise/Spiral Rule):
int*- pointer to intint const *- pointer to const intint * const- const pointer to intint const * const- const pointer to const int
Now the first
constcan be on either side of the type so:const int *==int const *const int * const==int const * const
If you want to go really crazy you can do things like this:
int **- pointer to pointer to intint ** const- a const pointer to a pointer to an intint * const *- a pointer to a const pointer to an intint const **- a pointer to a pointer to a const intint * const * const- a const pointer to a const pointer to an int- ...
If you're ever uncertain, you can use a tool like cdecl+ to convert declarations to prose automatically.
To make sure we are clear on the meaning of
const:int a = 5, b = 10, c = 15; const int* foo; // pointer to constant int. foo = &a; // assignment to where foo points to. /* dummy statement*/ *foo = 6; // the value of a can´t get changed through the pointer. foo = &b; // the pointer foo can be changed. int *const bar = &c; // constant pointer to int // note, you actually need to set the pointer // here because you can't change it later ;) *bar = 16; // the value of c can be changed through the pointer. /* dummy statement*/ bar = &a; // not possible because bar is a constant pointer.foois a variable pointer to a constant integer. This lets you change what you point to but not the value that you point to. Most often this is seen with C-style strings where you have a pointer to aconst char. You may change which string you point to but you can't change the content of these strings. This is important when the string itself is in the data segment of a program and shouldn't be changed.baris a constant or fixed pointer to a value that can be changed. This is like a reference without the extra syntactic sugar. Because of this fact, usually you would use a reference where you would use aT* constpointer unless you need to allowNULLpointers.From Stack Overflow: asked by ultraman, answered by Matt Price (CC BY-SA 4.0)
Is < faster than <=?
No, it will not be faster on most architectures. You didn't specify, but on x86, all of the integral comparisons will be typically implemented in two machine instructions:
- A
testorcmpinstruction, which setsEFLAGS - And a
Jcc(jump) instruction, depending on the comparison type (and code layout): jne- Jump if not equal -->ZF = 0jz- Jump if zero (equal) -->ZF = 1jg- Jump if greater -->ZF = 0 and SF = OF- (etc...)
Example (Edited for brevity) Compiled with
$ gcc -m32 -S -masm=intel test.cif (a < b) { // Do something 1 }Compiles to:
mov eax, DWORD PTR [esp+24] ; a cmp eax, DWORD PTR [esp+28] ; b jge .L2 ; jump if a is >= b ; Do something 1 .L2:And
if (a <= b) { // Do something 2 }Compiles to:
mov eax, DWORD PTR [esp+24] ; a cmp eax, DWORD PTR [esp+28] ; b jg .L5 ; jump if a is > b ; Do something 2 .L5:So the only difference between the two is a
jgversus ajgeinstruction. The two will take the same amount of time.I'd like to address the comment that nothing indicates that the different jump instructions take the same amount of time. This one is a little tricky to answer, but here's what I can give: In the Intel Instruction Set Reference, they are all grouped together under one common instruction,
Jcc(Jump if condition is met). The same grouping is made together under the Optimization Reference Manual, in Appendix C. Latency and Throughput.Latency — The number of clock cycles that are required for the execution core to complete the execution of all of the μops that form an instruction.
Throughput — The number of clock cycles required to wait before the issue ports are free to accept the same instruction again. For many instructions, the throughput of an instruction can be significantly less than its latency
The values for
Jccare:Latency Throughput Jcc N/A 0.5with the following footnote on
Jcc:- Selection of conditional jump instructions should be based on the recommendation of section Section 3.4.1, “Branch Prediction Optimization,” to improve the predictability of branches. When branches are predicted successfully, the latency of
jccis effectively zero.
So, nothing in the Intel docs ever treats one
Jccinstruction any differently from the others.If one thinks about the actual circuitry used to implement the instructions, one can assume that there would be simple AND/OR gates on the different bits in
EFLAGS, to determine whether the conditions are met. There is then, no reason that an instruction testing two bits should take any more or less time than one testing only one (Ignoring gate propagation delay, which is much less than the clock period.)Edit: Floating Point
This holds true for x87 floating point as well: (Pretty much same code as above, but with
doubleinstead ofint.)Read the rest at the sourceFrom Stack Overflow: asked by Vinícius, answered by Jonathon Reinhart (CC BY-SA 4.0)
- A
The Definitive C++ Book Guide and List
Beginner
Introductory, no previous programming experience
Book Author(s) Description review C++ Primer*
* Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.Stanley Lippman, Josée Lajoie, and Barbara E. Moo (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review] Programming: Principles and Practice Using C++ Bjarne Stroustrup, 3rd Edition - April 22, 2024 (updated for C++20/C++23) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners. Introductory, with previous programming experience
Book Author(s) Description review A Tour of C++ Bjarne Stroustrup (2nd edition for C++17, 3rd edition for C++20) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition. Accelerated C++ Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000 This basically covers the same ground as the C++ Primer, but does so in a quarter of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review] Best practices
Read the rest at the sourceFrom Stack Overflow: asked by grepsedawk, answered by Johannes Schaub - litb (CC BY-SA 4.0)
How do I iterate over the words of a string?
For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL.
#include <iostream> #include <string> #include <sstream> #include <algorithm> #include <iterator> int main() { using namespace std; string sentence = "And I feel fine..."; istringstream iss(sentence); copy(istream_iterator<string>(iss), istream_iterator<string>(), ostream_iterator<string>(cout, "\n")); }Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic
copyalgorithm.vector<string> tokens; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens));... or create the
vectordirectly:vector<string> tokens{istream_iterator<string>{iss}, istream_iterator<string>{}};From Stack Overflow: asked by Ashwin Nanjappa, answered by Zunino (CC BY-SA 4.0)
How to set, clear, and toggle a single bit?
Setting a bit
Use the bitwise OR operator (
|) to setnth bit ofnumberto1.// Can be whatever unsigned integer type you want, but // it's important to use the same type everywhere to avoid // performance issues caused by mixing integer types. typedef unsigned long Uint; // In C++, this can be template. // In C11, you can make it generic with _Generic, or with macros prior to C11. inline Uint bit_set(Uint number, Uint n) { return number | ((Uint)1 << n); }Note that it's undefined behavior to shift by more than the width of a
Uint. The same applies to all remaining examples.Clearing a bit
Use the bitwise AND operator (
&) to set thenth bit ofnumberto0.inline Uint bit_clear(Uint number, Uint n) { return number & ~((Uint)1 << n); }You must invert the bit string with the bitwise NOT operator (
~), then AND it.Toggling a bit
Use the bitwise XOR operator (
^) to toggle thenth bit ofnumber.inline Uint bit_toggle(Uint number, Uint n) { return number ^ ((Uint)1 << n); }Checking a bit
You didn't ask for this, but I might as well add it.
To check a bit, shift
numbernto the right, then bitwise AND it:// bool requires #include <stdbool.h> prior to C23 inline bool bit_check(Uint number, Uint n) { return (number >> n) & (Uint)1; }Changing the nth bit to x
There are alternatives with worse codegen, but the best way is to clear the bit like in
bit_clear, then set the bit to value, similar tobit_set.inline Uint bit_set_to(Uint number, Uint n, bool x) { return (number & ~((Uint)1 << n)) | ((Uint)x << n); }All solutions have been tested to provide optimal codegen with GCC and clang. See https://godbolt.org/z/Wfzh8xsjW.
From Stack Overflow: asked by JeffV, answered by Paige Ruten (CC BY-SA 4.0)
C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?
First, you have to learn to think like a Language Lawyer.
The C++ specification does not make reference to any particular compiler, operating system, or CPU. It makes reference to an abstract machine that is a generalization of actual systems. In the Language Lawyer world, the job of the programmer is to write code for the abstract machine; the job of the compiler is to actualize that code on a concrete machine. By coding rigidly to the spec, you can be certain that your code will compile and run without modification on any system with a compliant C++ compiler, whether today or 50 years from now.
The abstract machine in the C++98/C++03 specification is fundamentally single-threaded. So it is not possible to write multi-threaded C++ code that is "fully portable" with respect to the spec. The spec does not even say anything about the atomicity of memory loads and stores or the order in which loads and stores might happen, never mind things like mutexes.
Of course, you can write multi-threaded code in practice for particular concrete systems – like pthreads or Windows. But there is no standard way to write multi-threaded code for C++98/C++03.
The abstract machine in C++11 is multi-threaded by design. It also has a well-defined memory model; that is, it says what the compiler may and may not do when it comes to accessing memory.
Consider the following example, where a pair of global variables are accessed concurrently by two threads:
Global int x, y; Thread 1 Thread 2 x = 17; cout << y << " "; y = 37; cout << x << endl;What might Thread 2 output?
Under C++98/C++03, this is not even Undefined Behavior; the question itself is meaningless because the standard does not contemplate anything called a "thread".
Under C++11, the result is Undefined Behavior, because loads and stores need not be atomic in general. Which may not seem like much of an improvement... And by itself, it's not.
But with C++11, you can write this:
Global atomic<int> x, y; Thread 1 Thread 2 x.store(17); cout << y.load() << " "; y.store(37); cout << x.load() << endl;Now things get much more interesting. First of all, the behavior here is defined. Thread 2 could now print
0 0(if it runs before Thread 1),37 17(if it runs after Thread 1), or0 17(if it runs after Thread 1 assigns to x but before it assigns to y).What it cannot print is
37 0, because the default mode for atomic loads/stores in C++11 is to enforce sequential consistency. This just means all loads and stores must be "as if" they happened in the order you wrote them within each thread, while operations among threads can be interleaved however the system likes. So the default behavior of atomics provides both atomicity and ordering for loads and stores.Now, on a modern CPU, ensuring sequential consistency can be expensive. In particular, the compiler is likely to emit full-blown memory barriers between every access here. But if your algorithm can tolerate out-of-order loads and stores; i.e., if it requires atomicity but not ordering; i.e., if it can tolerate
37 0as output from this program, then you can write this:Global atomic<int> x, y; Thread 1 Thread 2 x.store(17,memory_order_relaxed); cout << y.load(memory_order_relaxed) << " "; y.store(37,memory_order_relaxed); cout << x.load(memory_order_relaxed) << endl;The more modern the CPU, the more likely this is to be faster than the previous example.
Finally, if you just need to keep particular loads and stores in order, you can write:
Global atomic<int> x, y; Thread 1 Thread 2 x.store(17,memory_order_release); cout << y.load(memory_order_acquire) << " "; y.store(37,memory_order_release); cout << x.load(memory_order_acquire) << endl;Read the rest at the sourceFrom Stack Overflow: asked by Sarfaraz Nawaz, answered by Nemo (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA23 questions