C C QA - yszheda/wiki GitHub Wiki
// an integer
int a;
// a pointer to an integer
int* a;
// a pointer to a pointer to an integer
int** a;
// an array of 10 integers
int a[10];
// an array of 10 pointers to integers
int* a[10];
// a pointer to an array of 10 integers
int (*a)[10];
// a pointer to a function that takes an integer argument and returns an integer
int (*a)(int);
// a function that takes an integer argument and returns a pointer to an integer
int *a(int);
// an array of 10 pointers to functions that take an integer argument and return an integer
int (*a[10])(int);
- https://en.wikipedia.org/wiki/Volatile_(computer_programming)
- the volatile keyword in C language?
- Why is volatile needed in C?
- Realistic usage of the C99 'restrict' keyword?
- Is there a practical use for a
volatile restrict
pointer?
In C, the type of a character constant like 'a' is actually an int, with size of 4. In C++, the type is char, with size of 1.
http://david.tribble.com/text/cdiffs.htm
- Where is the best place to put the #ifdef __cplusplus extern “C” { #endif
- Using “extern C” on non function call related declarations
-
C++: a const that is outside all functions has file scope (default to internal linkage)
-
C defaults to external linkage for consts, while C++ defaults to internal linkage for consts.
-
In C++, a const doesn't necessarily create storage, while in C a const always creates storage.
// pointer to const
const int* p;
int const* p;
// const pointer
int * const p;
// const pointer to const
const int* const p;
int const* const p;
// const reference
const int& ref;
-
Temporary objects are always const -> use const references as function arguments to receive temporary objects.
-
static const member: compile-time constant
class A
{
static const int size = 100;
int i[size];
}
"enum hack" for old compiler
class A
{
enum { size = 100 };
int i[size];
}
- mutable variable: can be changed inside a const object
- http://stackoverflow.com/questions/621616/c-what-is-the-size-of-an-object-of-an-empty-class
- http://www.geeksforgeeks.org/why-is-the-size-of-an-empty-class-not-zero-in-c/
- Constructors and member initializer lists
- https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list
- A reference must always be initialized because the object it refers to already exists; a pointer can be initialized at any time.
- Once a reference is initialized to an object, it cannot be changed to refer to another object; a pointer can be pointed to another object at any time.
- There is no NULL references.
- The virtual mechanism doesn't work with the constructor and destructor.
-
- If you call a virtual function inside a constructor, only the local version of the function is used.
-
- If you call a virtual function inside a destructor, only the local version of the function is used.
-
. (Member Access or Dot operator)
-
?: (Ternary or Conditional Operator )
-
:: (Scope Resolution Operator)
-
.* (Pointer-to-member Operator )
-
sizeof (Object size Operator)
-
typeid (Object type Operator)
Check self-assignment!
class Byte
{
unsigned char b;
public:
Byte(unsigned char bb = 0): b(bb) {}
Byte(const Byte& other) { this.b = other.b }
Byte& operator=(const Byte& right)
{
if( this == &right )
{
return *this;
}
b = right.b;
return *this;
}
}
-
prefix ++/-- : unary
-
postfix ++/-- : binary
class Byte
{
unsigned char b;
public:
Byte(unsigned char bb = 0): b(bb) {}
Byte(const Byte& other) { this.b = other.b }
Byte& operator=(const Byte& right)
{
if( this == &right )
{
return *this;
}
b = right.b;
return *this;
}
// prefix: ++Byte
const Byte& operator++()
{
b ++;
return *this;
}
// postfix: Byte++
const Byte& operator++(int)
{
Byte before(b);
b ++;
return before;
}
}
No return type!
class A {};
class B
{
public:
operator A() const { return A(); }
};
- Java runs in a virtual machine.
- C++ natively supports unsigned arithmetic.
- In Java, parameters are always passed by value (or, with objects, their references are passed by value). In C++, parameters can be passed by value, pointer, or by reference.
- Java has built-in garbage collection.
- C++ allows operator overloading.
- C++ allows multiple inheritance of classes.
In gdb
:
(gdb) catch throw
- https://stackoverflow.com/questions/16989137/how-to-debug-c-runtime-errors
- Find Where a C++ Exception is Thrown
What are some disciplines for using multiple inheritance?
- M.I. rule of thumb #1: Use inheritance only if doing so will remove
if
/switch
statements from the caller code.
- inheritance is not for code-reuse.
- the primary purpose for inheritance is dynamic binding, and that is for flexibility.
- Composition is for code reuse, inheritance is for flexibility.
- M.I. rule of thumb #2: Try especially hard to use ABCs when you use MI.
- this rule of thumb tends to push people toward inheritance-for-interface-substitutability, which is always safe, and away from inheritance-just-to-help-me-write-less-code-in-my-derived-class, which is often (not always) unsafe.
- M.I. rule of thumb #3: Consider the “bridge” pattern or nested generalization as possible alternatives to multiple inheritance.
- C++ version of the GNU getopt function
- https://stackoverflow.com/questions/4007112/c-and-command-line-options
- https://coderwall.com/p/y3xnxg/using-getopt-vs-boost-in-c-to-handle-arguments
- https://gcc.gnu.org/onlinedocs/cpp/Macros.html
- https://www.cprogramming.com/tutorial/cpreprocessor.html
#include <string.h>
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
- [CMake] FILE relative path
- CMake: Convert relative path to absolute path, with build directory as current directory
- Getting base name of the source file at compile time
- How do I use FILE and LINE as default parameters in a constructor in c++?
-
https://www.boost.org/doc/libs/1_58_0/boost/current_function.hpp
-
What's the difference between PRETTY_FUNCTION, FUNCTION, func?
- How to check if the current operating system is Windows, Linux, or OSX?
- Which Cross Platform Preprocessor Defines? (WIN32 or __WIN32 or WIN32 )?
- 用宏区分操作系统和编译器
- Macros for GCC/G++ to differentiate Linux and Mac OSX?
$ touch dummy.hxx
$ cpp -dM ./dummy.hxx
#define __DBL_MIN_EXP__ (-1021)
#define __FLT_MIN__ 1.17549435e-38F
#define __CHAR_BIT__ 8
#define __WCHAR_MAX__ 2147483647
#define __DBL_DENORM_MIN__ 4.9406564584124654e-324
#define __FLT_EVAL_METHOD__ 0
#define __DBL_MIN_10_EXP__ (-307)
#define __FINITE_MATH_ONLY__ 0
#define __SHRT_MAX__ 32767
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __UINTMAX_TYPE__ long unsigned int
#define __linux 1
#define __unix 1
#define __linux__ 1
...
- How to count the number of arguments passed to a function that accepts a variable number of arguments?
- C++ preprocessor VA_ARGS number of arguments
#define VARIADIC_SIZE(...) std::tuple_size<decltype(std::make_tuple(__VA_ARGS__))>::value
-
https://www.reddit.com/r/cpp/comments/90noeh/c_binary_compatible_api_abi/
-
How does adding a private member variable break C++ ABI compatibility?
- How can I add reflection to a C++ application?
- 如何优雅的实现C++编译期静态反射
- C++ Reflection in under 100 lines of code
template<class Interface, class KeyT=std::string>
struct Factory {
typedef KeyT Key;
typedef std::auto_ptr<Interface> Type;
typedef Type (*Creator)();
bool define(Key const& key, Creator v) {
// Define key -> v relationship, return whether this is a new key.
return _registry.insert(typename Registry::value_type(key, v)).second;
}
Type create(Key const& key) {
typename Registry::const_iterator i = _registry.find(key);
if (i == _registry.end()) {
throw std::invalid_argument(std::string(__PRETTY_FUNCTION__) +
": key not registered");
}
else return i->second();
}
template<class Base, class Actual>
static
std::auto_ptr<Base> create_func() {
return std::auto_ptr<Base>(new Actual());
}
private:
typedef std::map<Key, Creator> Registry;
Registry _registry;
};
- https://stackoverflow.com/questions/5093460/how-to-convert-an-enum-type-variable-to-a-string
- https://stackoverflow.com/questions/21456262/enum-to-string-in-c11
- https://stackoverflow.com/questions/28828957/enum-to-string-in-modern-c-and-future-c17-c20
int a[];
int *ptr;
int cnt;
vector v1(a, std::end(a));
vector v2(ptr, ptr+cnt);
vector v3;
v3.assign(a, std::end(a));
- https://stackoverflow.com/questions/2434196/how-to-initialize-stdvector-from-c-style-array
- https://stackoverflow.com/questions/26909429/stdbegin-and-stdend-not-working-with-pointers-and-reference-why
- https://stackoverflow.com/questions/22957205/how-do-you-declare-a-pointer-to-a-c11-stdarray
- https://stackoverflow.com/questions/6210450/the-compiler-is-complaining-about-my-default-parameters
- https://stackoverflow.com/questions/38559323/redefinition-of-default-argument
- https://stackoverflow.com/questions/35940684/error-redefinition-of-default-parameter
- https://stackoverflow.com/questions/3615476/floating-point-exception
- https://stackoverflow.com/questions/1081250/why-is-this-a-floating-point-exception
- GCC版本问题引发的floating point exception
-
Use a new
typename
to deduce 'const char ' -
https://stackoverflow.com/questions/12061842/template-variable-as-string-instead-of-const-char
-
https://stackoverflow.com/questions/5992953/c-cannot-convert-const-char-to-stdstring
assert(a == b && "A is not equal to B");
assert(("A must be equal to B", a == b));
#ifndef NDEBUG
# define ASSERT(condition, message) \
do { \
if (! (condition)) { \
std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
<< " line " << __LINE__ << ": " << message << std::endl; \
std::terminate(); \
} \
} while (false)
#else
# define ASSERT(condition, message) do { } while (false)
#endif
- https://stackoverflow.com/questions/3767869/adding-message-to-assert
- https://stackoverflow.com/questions/3692954/add-custom-messages-in-assert
- https://stackoverflow.com/questions/43011737/is-it-better-to-include-cassert-or-assert-h
- https://stackoverflow.com/questions/18210270/what-is-the-difference-between-assert-and-static-assert
- Assert and Constexpr in C++11
- _DEBUG vs NDEBUG
- Where does the -DNDEBUG normally come from?
- When does GCC define NDEBUG? [duplicate]
template<size_t n> double f(double (&c)[n]);
- https://stackoverflow.com/questions/16505376/how-to-pass-array-to-function-template-with-reference
- https://stackoverflow.com/questions/10128159/pass-an-array-as-template-type
- https://stackoverflow.com/questions/1745942/c-template-parameter-in-array-dimension
template <size_t rows, size_t cols>
void process_2d_array_template(int (&array)[rows][cols])
{
std::cout << __func__ << std::endl;
for (size_t i = 0; i < rows; ++i)
{
std::cout << i << ": ";
for (size_t j = 0; j < cols; ++j)
std::cout << array[i][j] << '\t';
std::cout << std::endl;
}
}
- http://www.ficksworkshop.com/blog/post/exporting-functions-and-namespaces
- error LNK2019: unresolved external symbol
- Unresolved external symbol on used defined namespace
-
put specialized implementation into .cpp rather then header file
-
multiple definition of template specialization when using different objects
there are no arguments to 'memcpy' that depend on a template parameter, so a declaration of 'memcpy' must be available
- gcc取消头文件多层关联,需加入头文件声明,参考:https://gcc.gnu.org/onlinedocs/gcc/Name-lookup.html
- linux编译中error: no arguments depend on a template parameter, declaration of * must 解决
- GCC compile error : declaration of ‘strlen’ must be available
- There are no arguments that depend on a template parameter
#include <string>
#include <sstream>
template <typename T> std::string to_string(const T& n)
{
std::ostringstream stm;
stm << n;
return stm.str();
}
terminate called after throwing an instance of 'std::system_error' what(): Enable multithreading to use std::thread: Operation not permitted
-pthread
sprintf(aval,"%d",ival);
- Explicit specialization in non-namespace scope [duplicate]
- Explicit template specialization cannot have a storage class - member method specialization
- C++ 嵌套类类模板特化 error: explicit specialization?
#include <inttypes.h>
int64_t t;
printf("%" PRId64 "\n", t);
uint64_t i;
printf("%" PRIu64 "\n", i);
#include <cmath>
#include <cstdlib>
- Ambiguous overload call to abs(double)
- How to fix “error: call to 'abs' is ambiguous”
- g++ error: call of overloaded 'abs(unsigned int)' is ambiguous
- 'ISO C99 requires at least one argument for the “…” in a variadic macro' When specifically using c11 and -Wno-variadic-macros
- Variadic macros with 0 arguments in C99
- Variadic macro warning
- https://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html
- Standard alternative to GCC's ##VA_ARGS trick?
- Variadic macros with zero arguments
- Variadic macro with no arguments for its variadic parameter
- Bug 44317 - ,##VA_ARGS comma not eaten with -std=c++0x
- Comma omission and comma deletion
malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *)
&((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd))))
&& old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)
((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))
+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1)))
&& ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
call to function 'operator<<' that is neither visible in the template definition nor found by argument-dependent lookup
- https://clang.llvm.org/compatibility.html#dep_lookup
- Argument-dependent lookup
- Template definition can't find my function
- C++: Function Lookup in Templates
- private-members-access.cpp
- Access to private members: Safer nastiness.
- Access to private members. That's easy!
void f_impl(int a, float b) {
printf("%d %g\n", a, b);
}
#define f_impl(...) f_macro(__VA_ARGS__, 3.7)
#define f_macro(a, b, ...) f_impl(a, b)