C++

¡Supera tus tareas y exámenes ahora con Quizwiz!

How can you printf a pointer, or a floating point value in scientific notation?

"%p" or "%e" respectively.

What printf specifiers should you use for size_t and ptrdiff_t?

"%zu" for size_t, and "%td" for ptrdiff_t. (Or use a 'u' instead or 'u' or 'd' for hex instead of unsigned or signed integer).

What's the best way to printf an int so it is always prefixed by '0x' and always shows all 8 hex digits?

"0x%08x" (note that using "%#010x" will not print the '0x' if the value is 0).

Give an example for a literal for a double value of 1?

"1." (exponent and decimal digits are optional).

What are the 3 types of exception guarantees?

"No fail guarantee" - will not throw. "Strong guarantee" - if a function throws an exception no memory leak will occur and program state is unmodified (i.e commit or rollback semantics). "Basic guarantee" - if an exception occurs, no memory leak will occur and the program is still in a valid/usable state.

What are POD types?

"Plain Old Data" types. They are similar to C-structs. They are "aggregate" types which also may not have a destructor or user-defined copy assignment operators. All data-members must also be PODs. This means an object can be created/destroyed simply by copying/freeing the memory layout (i.e. no user defined logic needs to run).

What are some of the new attributes in C++17?

"[[fallthrough]]" indictes that a fallthrough in a switch statement is deliberate. "[[nodiscard]]" indicates that a return value should not be ignored. "[[maybe_unused]]" indicates that the lack of use of a variable or parameter should not generate a warning.

What are the unicode escape sequences?

"\uxxxx" or "\Uxxxxxxxx"

What are the floating point types and sizes?

"float" - typically 32-bits, "double" - typically 64-bits, and "long double" - typically 80-bits (but same as "double" in VC++)

What are the methods to add or find an element in a std:set

"insert" or "find", respectively. "find" returns an iterator to the element, or to set.end() if not found.

How can you implement a method by using a method from a base class in a derived class?

"using Base::Method" to copy the implementations for Method (useful for adding overloads without hiding the base version), and for copying all constructors (except the default).

What is the c++ way to write to the console?

#include <iostream> and then use std::cout, (e.g. std::cout << msg << "\n")

What is the purpose over 'override' and 'final', and where to they go?

'override' goes on the member decl and ensures it is overriding a base member virtual function. 'final' goes on the member of class decl, and ensures nothing tries to override (for virtual member) or derive from it (for class).

What is the value of "0x1.2p3"?

1 + ( 2/16) * 2^3 = (1 + 0.125) * 8 = 9

How do you specify an integer literal is an unsigned long long?

3ull (or 3llu)

What does including <tchar.h> give you?

A bunch of _t... and _T... definitions to map to either ASCII or Unicode APIs, depending on if _UNICODE is defined.

What does a 'mutable' data member enable?

A const member method can still modify that data member.

What is an initializer-list constructor?

A constructor that takes an initializer-list, e.g. "Foo(initializer_list<double> args){...}". Include header <initializer_list>.

What is the default type for the literal "3.14"?

A double. Use the "f" or "l" suffix for "float" or "long double" respectively

What is a "forwarding reference"?

A function argument that is an rvalue reference to a cv-unqualified function template parameter, e.g. "template<class T> void Foo(T&& arg);"

What is the member security for nested classes?

A nested class can access all the private and protected members of the outer class. The outer class can only access the public members of the nested class however.

What is the value category of the parameter 'w' in the following: void f(Widget&& w);

A parameter is always an lvalue, even if its type is an rvalue reference.

What is a "thunk"?

A piece of code injected (or passed) into another piece of code for it's use, e.g. to calculate something on demand. It could be passed in as a function pointer for example.

What are the binutils?

A set of low level binary utilities for assembling (as), linking (ld), examining binary files (objdump, readelf), etc. Some of these are invoked by GCC.

What could "trampoline" mean in a higher-level language?

A trampoline can be used to do continuation-passing style code. For example, a loop that iteratively calls functions that return 'thunks' to the next function to call to simulate 'tail calls'.

In what state are standard library objects after std::move?

A valid but unspecified state. That is, only the functions without preconditions, such as the assignment operator, can be safely used on the object after it was moved from.

How can implicit type conversion occur, and how can you prevent it?

A will implicitly convert to B if A has a type conversion operator (e.g. "A::operator B();"), or B has a constructor that takes one parameter of type A (e.g. "B(A src);"). Marking such members "explicit" will prevent the implicit conversion.

What is a "function-try-block" and it's main purpose?

Adds a try/catch around an entire body. The try is before the member initializers for a constructor. Any exception is automatically re-thrown after the handler for constructors/destructors. The main use is to respond to an exception thrown from the member initializer list in a constructor by logging and rethrowing, modifying the exception object and rethrowing, throwing a different exception instead, or terminating the program. They are rarely used with destructors or with regular functions.

How do you allocate space for a static data members?

Allocate space in an implementation file (e.g. Foo::sBar = true). Starting with C++17, you can allocate them inline in the class, e..g "static inline bool sBar = true".

What is the "pimpl" idiom? What is its main benefit?

Also called "private implementation" or "bridge pattern", an implementation is split into an interface class, which just has the same API - and forwards all calls - to the actually implementation class. The interface class only has one data member; a pointer to the forward declared implementation class. This can drastically reduce build times, as changing the implementation does not change the interface class the rest of the program uses.

What is a "jump table"?

Also called a "branch table", it is a sequence of jump instructions in memory that is indexed into to perform an "indirect branch"

What must you do if providing the move or copy assignment operations?

Also provide the corresponding move or copy constructors.

What is a COMDAT? How can it affect build optimization?

An abbreviation of the historical term "Common Data", it is a unit of packaging in an object file. The linker can discard identical COMDAT sections, so if individual functions are packaged as COMDATs (/Gy - on by default for optimized builds), or global data (/Gw - off by default), the linker can discard copies it doesn't need

What is an "aggregate" data type?

An array type, or class type with no user provided constructors, no private/protected non-static data members, no virtual member functions, no virtual/private/protected base classes. It may be initialized with a brace-init list.

How are stdcall names decorated?

An underscore (_) is prefixed to the name. The name is followed by the at sign (@) followed by the number of bytes (in decimal) in the argument list.

When declaring vars or type "auto", what is a gotcha that may result in copying?

Any const or ref on the type is removed. Use "const auto& v1 = foo()" to keep the qualifications on the type.

How many hex chars are in a hex escape sequence?

Any number, terminating at the first non-hex char, e.g. "\x1234world". However it must fit in the type for the literal (e.g. char, char16_t, etc..)

Why must class and struct definitions end with a semi-colon?

As an optional list of instances may be declared after the body, e.g. "struct foo {int a; int b;} x, y, z;"

What are some things the assignment operator needs to consider that the copy constructor doesn't?

As the rhs already exists: Duplication of any dynamically added memory, and if the object is being assigned to itself (e.g. "if (&rhs == this) return *this;").

What size is a "long" in C++?

At least 32-bits. On x64 platforms, it is 32-bits on Windows, and 64-bits on Unix/Linux.

What is the rule of 0?

Avoid needing the rule of 5, but not doing any dynamic memory operations in modern C++, and using the standard library containers.

How are __thiscall names decorated?

Because this calling convention applies only to C++, there is no C name decoration scheme. C++ names are decorated in an internal-only manner that includes an encoding for class, namespace, param types, return type, etc. "void __thiscall a::func1(int)" would be something like "?func1@a@@AAEXH@Z".

Do you mark a method as const in the declaration or definition?

Both

What are some of the major features of C++11

C++11 introduced move semantics, variadic templates, initializer lists, constexpr, range-based loops, etc..

What are some of the major features of C++14?

C++14 introduced std::make_unique, return type deduction, decltype(auto), generic lambda expressions, etc..

What are some of the early C++ standards?

C++98 (the first) and C++03 (technical updates). C++11, C++14, C++17.

What does the compiler generated default constructor do?

Calls the default constructor for all object members of the class, but does not initialize language primatives such as int, double, etc.

What are "class constants"?

Class members declared "static const". They can be initialized in the class definition without being declared "inline". These should be preferred over globals (or macros) if specific to a class.

Does the 'virtual' keyword go in front of the declaration, definition, or both?

Declaration only. (Note: It is not needed in derived classes overriding the method, but is recommended).

How can you get the compiler generated default constructor if you provide other constructors?

Declare "MyClass() = default" (or declare as normal and define as defaulted to avoid repeated inline instances)

How would you enable class C to be implicitly converter to an int?

Define a type conversion operator member, e.g. "operator int() {...}"

How do you define a Unicode entry point for your app?

Defined a 'wmain' function that takes a 'wchar_t #argv' param. (Or use '_tmain' with a _TCHAR #argv if using tchar.h).

What is the "offsetof" macro?

Defined in <cstddef>, "offsetof(type, member)" returned the byte offset of member from the start of type (which will always be 0 for the first member in a "standard layout" type).

Why might you explicitly delete method overloads, e.g. "int GetNum(double i) = delete"?

Do avoid the compiler doing implicit casts from the param type to another overload.

What are the underscore rules in identifier naming?

Don't define names at global scope that being with an "_", these are reserved for the compiler and standard library. Don't define names at any scope beginning with a double underscore, or underscore followed by an uppercase letter, there are reserved for any use.

What is the default compiler /O setting?

Favor fast code (/Ot), which does nothing unless /Og (global optimizations) is enabled, as the default is also /Od (disable optimizations). Using /O1 or /O2 is prefered to /Ot (or /Os).

What is the signature for the default assignment operator?

Foo& operator=(const Foo& rhs);

When resolving a binary operator function, where does the compiler look?

For a member function of the lhs that takes a param of the rhs, or a global function that takes the two params matching the operands. (It will also try to implicitly convert the rhs if it can).

When is using the ctor-initializer required?

For const or references data members, and base classes or members that have no default constructor.

What is the difference between "function parameter scope" and "function scope"?

Function scope is for labels. Labels are in scope throughout the entire function body (even before declaration). Function parameter scope begins at declaration, and ends at the end of the containing declaration.

What is the typeid operator for?

Gets the runtime time information (RTTI) for a type (which must have a vtable). This should mainly be used for logging or debugging, with virtual methods used for runtime type dependent behavior.

What is the x64 calling convention?

Given the expanded register set, x64 uses the __fastcall calling convention and a RISC-based exception-handling model. The __fastcall convention uses registers for the first four arguments and the stack frame to pass additional arguments. Note that in a 64-bit environment, functions are not decorated.

What does "cv-qualified" mean?

Having the 'const' or 'volatile' type qualifiers.

What are some examples of lvalues?

If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue.

What are some examples where you need a default constructor?

If creating an array of instances (e.g. "auto f = new Foo[10];") or if using some standard containers like std::vector.

What is the macro NDEBUG used for?

If it is defined, then the assert macro from <assert.h> or <cassert> evaluated to no code (else it prints and calls abort() if the expression is false).

When is a default move constructor or move assignment operator generated?

If the class does not have any user defined move, copy, or destructor implementations.

What should a derived class do for the copy constructor and assignment operator?

If the derived version is not the default, call the base version (in the init list for the copy constructor, and after the this = &rhs check for assignment operator).

Can you delete a pointer to an object with a (non-trivial) destructor if the type is not clear from the pointer expression?

If the object being deleted has incomplete class type at the point of deletion, and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined

What is the rule of 5?

If you allocate any dynamic memory, you should probably implement a user defined destructor, copy constructor, move constructor, copy assignment, and move assignment.

Where are values such as INT_MIN or SIZE_MAX defined?

In <limits.h>. (For C++, you can include <limits> and use std::numeric_limits<T>::min(), max(), etc.)

What is wrong with the following code?: void f(char *name){/*...*/}; f("test");

In C++, you cannot pass a string literal for a char *. The parameter would need to be "const char *".

What are structured bindings?

In C++17, you can do something like: auto [v1, v2, v3] = someVector;

How can you explicitly remove a default constructor if not providing other constructors?

In the class declaration, "Foo() = delete".

In what order are ctor-initializers run?

In the order declared in the class, not in the order given on the constructor.

What is the order of initialization of non-local variables (i.e. static members of a class, or globals)?

In the order they are defined in a source file, but undefined across source files.

What are the two operations that invoking new or delete perform for an object type?

Invoking new first calls operator new to allocate the memory, then calls the object constructor. Delete does the reverse (calls the destructor, then invokes operator delete).

What is a "universal reference"?

It can bind to rvalues or lvalues. If a function template parameter has a type "T&&" for a deduced type "T", or an object is declared using "auto&&" it is a universal reference.

What happens if a ctor throws an exception? Does the dtor run?

It does not run. Automatic variables initialized before the exception will have their destructors invoked.

What is the "final" keyword on methods or classes for?

It gives a compile time error on a method if the method is not virtual or is overridden in a derived class, or on a class if the class is derived from (respectively)

What is the "override" keyword on methods for?

It gives a compile time method if the method is not actually overriding a virtual method in a base class.

What is an "indirect branch"?

It is a branch (call/jump) to a location other than a direct address, e.g. to a location stored in a register or in memory

Does this add up to 16: "0xE+2.0"?

It is a syntax error due to the "maximal munch". Use "(0xE)+2.0"

What is a "retpoline"?

It is a trampoline used to perform a return. It is often used protect indirect branches from speculative execution for security reasons.

What is the recommended way to "down cast'?

It is best avoided, but if needed, use dynamic_cast<type>. It typically uses the vtable info, so requires a virtual method on the type. It returns a null pointers if it cannot cast to a pointer, or throws a std::bad_cast for an invalid reference cast.

What is the _DEBUG macro?

It is defined if MSVC compiles with the debug libraries (i.e. /MTd or /MDd is specified).

What does std::move do?

It is exactly equivalent to a static_cast to an rvalue reference type.

When is the default assignment operator generated and what does it do?

It is generated whenever you don't provide one, and since C++11, if the class has no user defined copy constructor or destructor, in which case you can add it via the "Foo& operator=(const Foo& rhs) = default" syntax).

The new function in the C++ standard does what if the memory allocation fails?

It throws a std::bad_alloc exception

For static members, do you need the static keyword on the declaration and definition?

Just the declaration.

What are the string literal prefixes/suffixes?

L, u8, u, and U for wide string (wchar_t*), utf8 (char*), utf16 (char16_t*), and utf32 (char32_t*) respectively. From C++14 onward you can suffix with "s" to indicate this is a std::string literal (or other char type depending on prefix).

What is LTCG?

Link Time Code Generation (or Whole Program Optimization) allows the linker to optimize code across modules, and do additional removal of duplicate (/OPT:ICF) or unreferenced (/OPT:REF) code. /GL enables for the compiler, which will imply /LTCG in the linker.

How many octal chars are in an octal sequence?

Max 3, or terminates early at a non-octal char. "\0" is useful as a null char, e.g. "\377\0"

What is unique about virtual methods in the context of constructors and destructors?

Methods overriden in derived classes are not called. The implementation in the class being constructed/destructed is called - even if virtual and overridden.

What are "intrinsic functions" (e.g. _InterlockedCompareExchange and memcpy) and the "/Oi" option?

Most functions are contained in libraries, but some functions are built in (that is, intrinsic) to the compiler. These are referred to as intrinsic functions or intrinsics. The code is usually inserted inline, avoiding the overhead of a function call and allowing highly efficient machine instructions to be emitted for that function.

Should you generally provide move operations on a copyable type?

Move operations for copyable types are strictly a performance optimization and are a potential source of bugs and complexity, so avoid defining them unless they are significantly more efficient than the corresponding copy operations.

What is the value of using nullptr over NULL?

NULL is an int value, so may choose the wrong overload for a function if one takes int and one takes a pointer.

Does overloading an operator like "+" also overload its shorthand "+="?

No, those must be implemented separately. They return the modified object, not a new temporary, and always require the lhs be an object of the type (so no benefit to using a global function).

Can you pass an lvalue to a parameter that expects an r-value reference?

No.

Are there negative integer literals?

No. "-3" is the unary negation operator applied to 3

Does a 'constexpr' function guarantee it will be evaluated at compile time?

No. It could be compile time if possible, else runtime.

Can static_cast add or remove constness?

No. Use const_cast to remove const.

Can static_cast convert between pointers of unrelated types?

No. Use reinterpret_cast.

What's the difference between the _T and _TEXT macros?

Nothing, they both map to the __T macro, which maps __T(x) to L##x if _UNICODE is defined, else just to x.

What are the two types of macros?

Object-like, which take no arguments, and function-like, which has arguments following a paren directly after the name.

What is a raw string literal?

Of the format R"<delim>(<chars>)<delim>" (with an optional string literal prefix). Eg. u8R"abc(Hello, world)abc". Newlines and backslashes within a raw literal remain as-is (i.e. are not stripped or escaped)

What is the difference between "wchar_t" and "char16_t" types?

On Windows, none, as wchar_t is 16 bits. However the C++ standard states wchar_t should be able to hold any unicode character code-point (e.g. up to 0x10FFFF), and char16_t holds UTF16 code-units.

Where does the 'explicit' keyword go?

Only in the class definition. It only makes sense on constructors that take one parameter.

Where may the 'virtual' keyword go?

Only in the initial decl of a member function that is to be virtual (i.e. not on the derived classes or impls). It may also be used on base classes to indicate that derived classes should share only one base, even if inherited multiple times.

What is one key difference between operator overloads that are members versus global functions?

Only parameters will be implicitly converted, so a member operator method will not implicitly convert the lhs.

Do you specify the defaults for parameters in the declaration or definition?

Only the declaration.

Objects that have been moved from are placed in a valid but unspecified state. What does that mean?

Only the functions without preconditions, such as the assignment operator (or e.g. "empty()"), can be safely used on the object after it was moved from.

Can you redefine a macro?

Only to exactly the same definition, else you need to #undef it first before defining it again.

What is wrong with this code? ctor(const std::string text): value(std::move(text)) {...}

Param 'text' is declared as 'const', so it cannot be moved from. (It will compile, but copy construct 'value').

How can you specify that a function doesn't return a value (e.g. it only terminate the program, or throws an exception, etc.)?

Place the [[noreturn]] attribute on it.

What variable types of a base class will call a derived types virtual method if the object is actually derived from base?

Pointers and references. Casting a derived to a base causes it to act like the base class.

How can you avoid needing a default constructor if declaring an array on the stack?

Provide initializers, e.g. "Foo f[] = {Foo(1), Foo(2)};"

What is RAII?

Resource acquisition is initialization. This idiom ties management of such resources to the lifespan of automatic variables.

What is the size and sign of "char"?

Sign is platform/compiler dependent (typically signed on x86/x64 and unsigned on ARM). Size is one byte, large enough to hold any UTF8 code unit (e.g. min 8 bits). It is a distinct type to either "signed char" or "unsigned char"

What is a "trampoline" in low-level programming?

Simply a location that when branched to, immediately branches to another location. They can also be used to convert calling conventions.

How is default static member initialization different to data member initialization?

Statics are initialized to 0 by default.

What is SFINAE?

Substitution Failure Is Not An Error. When substitution during overload resolution causes a failure, it is not a compiler error, the specialization is just removed from the set of candidates.

What do "##", "#", and "#@" mean in a macro?

The "token-pasting operator" (##), joins the tokens either side into one. The "stringizing operator" (#) encloses its argument in double quotes. The "charizing operator" (#@) encloses its argument in single quotes.

What is the difference between <stdio.h> and <cstdio>?

The C++ header <cstdlib> provides its definitions within the namespace std. It may also provide these names within the global namespace. The C header <stdlib.h> provides the same definitions within the global namespace. It may also provide these names within the namespace std.

What is the C runtime library?

The CRT is the part of the C++ Standard Library that incorporates the ISO C99 standard library.

What does the UCRT contain?

The Universal CRT (UCRT) contains the functions and globals exported by the standard C99 CRT library.

Should you use C++ interfaces between separately compiled components?

The Visual C++ compiler ABI have historically changed between major compiler releases. This is especially the case for STL containers, where container sizes have varied a lot between compiler releases. Microsoft therefore recommends against using C++ interfaces at module boundaries when one wants to enable client code compiled using a different compiler version. Instead of C++, Microsoft recommends using C or COM interfaces, which are designed to have a stable ABI between compiler releases.

What is the stdcall calling convention?

The __stdcall calling convention is used to call Win32 API functions (WINAPI). The callee cleans the stack, so the compiler makes vararg functions __cdecl.

What is the thiscall calling convention?

The __thiscall calling convention is used on member functions and is the default calling convention used by C++ member functions that do not use variable arguments. Under __thiscall, the callee cleans the stack, which is impossible for vararg functions. Arguments are pushed on the stack from right to left, with the this pointer being passed via register ECX, and not on the stack, on the x86 architecture. vararg member functions use the __cdecl calling convention. All function arguments are pushed on the stack, with the this pointer placed on the stack last.

How do you use variadic macros?

The ellipsis may be specified as the final formal argument in a macro definition, and the replacement identifier __VA_ARGS__ may be used in the definition to insert the extra arguments. __VA_ARGS__ is replaced by all of the arguments that match the ellipsis, including commas between them. e.g. "#define CHECK1(x, ...) if (!(x)) { printf(__VA_ARGS__); }"

What is the difference between #include <header.h> and #include "header.h"?

The latter searches additional include dirs first, then the same locations as the former. While "implementation defined", the former is usually only for standard header files in system include paths, and the latter for custom header files by searching the source file path first.

Why is using a ctor-initializer for a member more efficient than initializing members in the body?

The object is already initialized by the time the body executes, and is just assigning a value. The ctor-initializer will construct the member as specified.

What is the resulting type of subtracting two pointers?

The pointers must be of the same type & array, and the result is of type ptrdiff_t.

What is in "class scope"?

The potential scope of a name declared in a class begins at the point of declaration and includes the rest of the class body and all function bodies (even if defined outside the class definition or before the declaration of the name), default arguments, exception specifications, in-class brace-or-equal initializers, contract conditions (since C++20), and all these things in nested classes, recursively.

What is namespace scope?

The potential scope of any entity declared in a namespace begins at the declaration and consists of the concatenation of all namespace definitions for the same namespace name that follow, plus, for any using-directive that introduced this name or its entire namespace into another scope, the rest of that scope.

What are some examples of prvalues?

The result of calling a function whose return type is not a reference is a prvalue. The value of a literal such as 12, 7.3e5, or true is also a prvalue.

Of what type is an integer literal in source by default?

The smallest int type it will fit in while honoring the suffix (int, long, long long, or unsigned)

What is the type of an integer literal?

The smallest size of "int" that will fit the value. This will be signed for a decimal literal, and either signed of unsigned for a hex/octal/binary. If "u" suffix is used it will be unsigned. If "l" or "ll" suffix is used it will be at least "long" or "long long" respectively.

Why must all data-members be of the same access control for a type to be of "standard layout"?

The standard requires that memory layout for non-static data members of the same access control be in the order declared, but those with different access control may be grouped together.

Do you have try/catch/finally in C++?

There is no 'finally'. Use RAII to ensure resources are cleaned up.

What happens to two adjacent string literals?

They are concatenated (after the preprocessor phase). i.e. This is handy for escape sequences, e.g. "\x05five" is not the same as "\x05" "five" (the former is hex 0x5f followed by "ive")

Can 'inline' and 'constexpr' functions go in the header file?

They can be defined multiple times, but once per translation unit, and should be identical (i.e. the same header can be included in multiple .cpp files). constexpr functions are implicitly inline.

What do std::move and std::forward do at runtime?

They generate no code. The are merely function templates that perform casts. std::move unconditionally casts its argument to an rvalue, while std::forward performs this cast only if a particular condition is fulfilled.

What are some of the advantages of std::array over old C style arrays?

They know their own size, don't automatically convert to pointers, and you can use iterators on them.

What is static linking of the CRT and what is its benefit?

This links the library object code directly into the application. This creates a single binary without a DLL dependency, so that you don't have to deploy the Visual C++ library files separately.

Why might you use const_cast?

To delegate a non-const member to a const version, e.g. "return const_cast<Foo&>(std::as_const(*this).myFn(x, y));"

What are "storage class specifiers"?

Together with the scope of the name, they control two independent properties of the name: its storage duration and its linkage. They are: auto, static, extern, thread_local. (register is deprecated).

Why are character sequences starting with "??" dangerous?

Trigraphs (removed in C++17) are parsed and replaced before comments and strings are recognized. They support very old char sets, and do substitution, e.g. "??/" becomes "\", and "??<" becomes "{". Alternative tokens (e.g. "<%" for "{" and "%:" for "#") are still supported, but are alternate tokens, not parser substitutions.

What's the difference between defining UNICODE and _UNICODE?

UNICODE affects the Windows APIs, _UNICODE the standard C/C++ APIs. You need to define UNICODE to get the right mapping to the ...A or ...W versions of the Win32 APIs. You need _UNICODE to map the _tsc... versions or the CRT APIs to the str... or wcs... APIs.

How are cdecl names decorated?

Underscore character (_) is prefixed to names, except when __cdecl functions that use C linkage are exported.

What is the difference between a scoped and unscoped enumeration?

Unscoped ("enum color {red, blue};") introduces names (red, blue) that are in scope after the end of the declaration. Scoped enums ("enum class color {red, blue = red + 2};"), have members only in scope within the declaration, and must be qualified ("color::red") after the declaration.

What are the ways to get 'internal linkage' for a function? What is recommended?

Use the "static" keyword on the function, or use an anonymous namespace ("namespace { /*...*/ }"). The latter is recommended.

How can you printf a hexadecimal value with a leading '0x'?

Use the format specifier "%#x"

How could you check properties of a type at compile time?

Use type traits and static_assert, e.g. "static_assert(std::is_copy_constructible<T>::value, "Swap requires copying");"

What is a "delegating constructor" and how is it written?

When a constructor just calls another constructor of the same class. It must be the only call in the ctor-initializer, e.g. "Foo::Foo(..) : Foo::Foo(true){...}".

When is a default copy constructor generated?

Whenever you don't provide one, and since C++11, if the class has no user defined copy assignment operator or destructor, in which case you can add it via the "Foo(const Foo&) = default" syntax).

How should you mark a function as deprecated?

With the [[deprecated]] attribute.

What is a "function-local predefined variable"

Within the function body, the function-local predefined variable __func__ has block scope and static storage duration, and is defined as: static const char __func__[] = "function-name";

Should you throw exceptions from constructors or destructors?

Yes for constructors - there's no other good way to communicate failure. No for destructors - these may be running as an effect of handling another exception. C++ will "terminate()" if an exception is thrown from a destructor.

Can a derived class override private methods from a base class?

Yes, and methods in the base class will call the derived version if they are virtual.

Can ptrdiff_t overflow?

Yes, and the result is undefined if a value would be larger than PTRDIFF_MAX. For example, as it is a signed 32-bit value, if the array is over 2GB in size. (Many libraries will not let malloc allocate >= 2GB, which avoids this issue).

Can static_cast convert a base pointer to a derived pointer.

Yes, but this is unsafe. Prefer dynamic_cast.

Can you take a reference to a return value?

Yes, if it is const (e.g. "const std::string& val = getString();". The reference keeps the object alive until it goes out of scope.

Can you assign to the result of a function call?

Yes, if the return type is an lvalue reference, e.g. "int& FindVal(){...}; FindVal() = 10;"

Can you use a hexadecimal floating point literal?

Yes, since C++17. Use 'p' for the (not optional) exponent. Eg. "0x0p-1" or "0xa.bp10l"

Can the signature of a method that is overriden change in any way?

Yes, the return type can be "covariant" (i.e. a derived type of the type returned from the base implementation).

Is there an order required for the override or final keywords on declarations?

Yes, they are not part of the "declarator", which includes things like "noexcept", and must come after it.

Can you have non-static 'const' data members in a class?

Yes, they should be initialized in the ctor-initializers or in-class initializers. Often the assignment operator will be deleted (as the const member cannot be changed).

Can a function or class be constexpr?

Yes, with many restrictions. It must be able to evaluate at compile time, so cannot throw exceptions, call new/delete, use non constexpr compatible types (e.g. virtual methods or base classes, etc.), and many more.

Can you modify the value in a parameter of type r-value reference?

Yes.

Can you delete and null pointer? Why or why not?

Yes. That means if new fails (are returns a null pointer), calling delete on the result is benign

What value type of exception should you throw?

You can throw any type, though deriving from std::exception is preferred. (Some are defined in <exception>).

Describe the cdecl calling convention.

__cdecl is the default calling convention for C and C++ programs. Because the stack is cleaned up by the caller, it can do vararg functions. The __cdecl calling convention creates larger executables than __stdcall, because it requires each function call to include stack cleanup code.

What is the difference between accessing a char in a std::string using the at() method or the [] indexing operator?

at() is bounds checked and will throw std::out_of_range if pos >= size(), whereas operator[] is undefined if out of bounds.

How would you make a unique_ptr to an array of 10 employees?

auto employees = make_unique<Employee[]>(10);

What is wrong with the statement: "auto foo = std::as_const(bar)"?

auto strips away const (and reference), so the resulting foo is still not const.

What are the 4 C++ casts?

const_cast, static_cast, dynamic_cast, and reinterpret_cast.

What is the difference between glibc and libstdc++

glibc is the C runtime/APIs, and is closely linked to the kernel on Linux. libstdc++ is the C++ portion, which depends on glibc functionality.

What are the 5 value categories and their major attributes?

prvalue (pure rvalue - no identity and can be moved from), xvalue (eXpiring value - has identity and can be moved from), lvalue (has identity and can't be moved from). A glvalue (generalized lvalue) han an identitiy and is either an lvalue or an xvalue. An rvalue is movable and is either a prvalue or an an xvalue.

What cast do you need to convert a void* to a Foo*?

reinterpret_cast. (Note: Converting a pointer TO a void* doesn't require a cast).

How can you get a substring from a string?

s.substr(size_t pos, size_t count)

What should you use to return how many characters are in a std::string?

size() or length(), they are identical. size() exists for compatibility with other containers.

What's the difference between size() and capacity on a std::vector?

size() returns the number of elements currently stored. capacity() returns how many could be stored in the currently allocated memory.

How can you do bound checked style printf to a buffer?

snprintf(buffer, count, format, ...). (Note: The _s versions on MSVCRT are slightly different to the standard).

What is a high level difference between static_cast and dynamic_cast?

static_cast is a compile-time check. dynamic_cast is a runtime check using RTTI (runtime type information).

What produces an xvalue expression?

std::move, and the result of calling a function whose return type is an rvalue reference is an xvalue.

What are the general contains for storing sets in C++?

std::set and std::unordered_set. set is stored ordered, generally as red-black trees, while unordered_set is stored unordered, generally as a hash table.

What is the preferred way to get the number of elements in an array or vector?

std::size(obj); // include <iterator> (or array, list, map, string, or vector)

What is the basic stack container in the STL and is core methods?

std::stack (include <stack>). void push(cont T& val), T top(), void pop();

What is the size_t type for?

todo

How would you define a type alias for a function that takes 2 ints and returns a bool?

using MyFunc = bool (*)(int, int);


Conjuntos de estudio relacionados

Chapter 1: End of Chapter Practice Quiz

View Set

Read Theory Answers (36 Passages)

View Set

Chapter 31: Assessment of Immune Function

View Set