SlideShare a Scribd company logo
1 of 62
Download to read offline
C/C++ tricks
David Barina
April 13, 2018
David Barina C/C++ tricks April 13, 2018 1 / 59
Duff’s device
switch (count % 8) {
case 0: do { *to = *from ++;
case 7: *to = *from ++;
case 6: *to = *from ++;
case 5: *to = *from ++;
case 4: *to = *from ++;
case 3: *to = *from ++;
case 2: *to = *from ++;
case 1: *to = *from ++;
} while (( count -= 8) > 0);
}
David Barina C/C++ tricks April 13, 2018 2 / 59
[] operator
const char *a = "0123456789 abcdef";
int i = ...;
char digit = a[i];
char digit = *(a+i);
David Barina C/C++ tricks April 13, 2018 3 / 59
[] operator
const char *a = "0123456789 abcdef";
int i = ...;
char digit = a[i];
char digit = *(a+i);
char digit = i[a];
David Barina C/C++ tricks April 13, 2018 4 / 59
Swap algorithm
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void swap(int *a, int *b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
David Barina C/C++ tricks April 13, 2018 5 / 59
--> operator
int x = 10;
while( x --> 0 )
while( 0 <-- x )
while( 0 <---- x )
David Barina C/C++ tricks April 13, 2018 6 / 59
Catching exceptions in initializer lists
struct A {
A() : b() { ... }
B b;
};
A() : b() {
try {
...
} catch (...) {
...
}
}
David Barina C/C++ tricks April 13, 2018 7 / 59
Catching exceptions in initializer lists
struct A {
A() : b() { ... }
B b;
};
A() try : b() {
...
} catch (...) {
...
}
David Barina C/C++ tricks April 13, 2018 8 / 59
Namespace aliases
namespace foo {
namespace bar {
namespace baz {
int qux = 42;
}
}
}
namespace fbz = foo::bar::baz;
std:: cout << fbz::qux << ’n’;
David Barina C/C++ tricks April 13, 2018 9 / 59
Namespace aliases
#if THREADS_ARE_SUPPORTED_ON_THE_PLATFORM
namespace lib = project ::lib:: impl_with_threads ;
#else
namespace lib = project ::lib:: impl_wout_threads ;
#endif
David Barina C/C++ tricks April 13, 2018 10 / 59
Storage class specifiers
typedef int type;
int typedef type;
// static , extern
David Barina C/C++ tricks April 13, 2018 11 / 59
Integer overflow
for(char c = 100; c > 0; c++)
printf("%in", (int)c);
David Barina C/C++ tricks April 13, 2018 12 / 59
Integer promotion
char c = ’X’;
cout << c;
David Barina C/C++ tricks April 13, 2018 13 / 59
Integer promotion
char c = ’X’;
cout << c;
cout << +c;
David Barina C/C++ tricks April 13, 2018 14 / 59
Polyglot
$CC -std=c90 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C90
$CC -std=c99 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C99
$CC -std=c11 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C11 or newer
$CXX -std=c++98 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C++03 or older
$CXX -std=c++03 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C++03 or older
$CXX -std=c++11 -pedantic -Wall -Wextra prog.c && ./a.out
I am compiled with C++11 or newer
David Barina C/C++ tricks April 13, 2018 15 / 59
Polyglot
if( sizeof(’a’) == sizeof(char) )
{
// compiled with C++
}
else
{
// compiled with C
}
David Barina C/C++ tricks April 13, 2018 16 / 59
Polyglot
#define R(U) sizeof(U"a"[0])
if( R("") == 4 )
{
// C++11 or newer
}
else
{
// C++03 or older
}
David Barina C/C++ tricks April 13, 2018 17 / 59
Polyglot
if( 2 // **/2
== 2 )
{
if( R("") == 4 )
{
// C11 or newer
}
else
{
// C99
}
}
else
{
// C90
}
David Barina C/C++ tricks April 13, 2018 18 / 59
Named loops
David Barina C/C++ tricks April 13, 2018 19 / 59
Named loops
outer: for( ... )
{
inner: for( ... )
{
...
goto outer;
}
}
David Barina C/C++ tricks April 13, 2018 20 / 59
Named loops
for( ... )
{
for( ... )
{
...
goto after;
}
}
after :;
David Barina C/C++ tricks April 13, 2018 21 / 59
Named loops
if( 0 )
after :;
else
for( ... )
{
for( ... )
{
...
goto after;
}
}
David Barina C/C++ tricks April 13, 2018 22 / 59
Named loops
[](){
for( ... )
{
for( ... )
{
...
return;
}
}
}();
David Barina C/C++ tricks April 13, 2018 23 / 59
Copy-and-swap
class dumb_array
{
public:
dumb_array(std:: size_t size = 0);
dumb_array(const dumb_array& other );
~dumb_array ();
private:
std:: size_t mSize;
int* mArray;
};
David Barina C/C++ tricks April 13, 2018 24 / 59
Copy-and-swap
dumb_array& operator =( const dumb_array& other)
{
if (this != &other) // (1)
{
delete [] mArray; // (2)
mArray = nullptr; // (2)
mSize = other.mSize; // (3)
mArray = mSize ? new int[mSize]
: nullptr; // (3)
std:: copy(other.mArray ,
other.mArray + mSize ,
mArray ); // (3)
}
return *this;
}
David Barina C/C++ tricks April 13, 2018 25 / 59
Copy-and-swap
friend void swap(dumb_array& first ,
dumb_array& second) // nothrow
{
using std:: swap;
swap(first.mSize , second.mSize );
swap(first.mArray , second.mArray );
}
dumb_array& operator =( dumb_array other) // (1)
{
swap (*this , other ); // (2)
return *this;
}
David Barina C/C++ tricks April 13, 2018 26 / 59
Member call on null pointer
class A {
int x;
public:
void foo() {
std:: cout << "foo" << std:: endl;
x = 0;
}
};
int main () {
A *a = 0;
a->foo ();
}
David Barina C/C++ tricks April 13, 2018 27 / 59
Member call on null pointer
class A {
int x;
public:
void foo() {
std:: cout << "foo" << std:: endl;
x = 0;
}
};
int main () {
A *a = 0;
a->foo ();
}
foo
Neopr´avnˇen´y pˇr´ıstup do pamˇeti (SIGSEGV)
David Barina C/C++ tricks April 13, 2018 27 / 59
Member call on null pointer
class A {
int x;
public:
void bar() {
std:: cout << "bar" << std:: endl;
}
};
int main () {
A *a = 0;
a->bar ();
}
David Barina C/C++ tricks April 13, 2018 28 / 59
Member call on null pointer
class A {
int x;
public:
void bar() {
std:: cout << "bar" << std:: endl;
}
};
int main () {
A *a = 0;
a->bar ();
}
bar
David Barina C/C++ tricks April 13, 2018 28 / 59
Integer overflow
int a = /* something */;
int b = /* something */;
a += b;
if( a < 0 ) {
/* ... */
}
David Barina C/C++ tricks April 13, 2018 29 / 59
Integer overflow
int a = /* something */;
int b = /* something */;
a += b; /* UB */
if( a < 0 ) { /* unreliable test */
/* ... */
}
David Barina C/C++ tricks April 13, 2018 30 / 59
Integer overflow
int a = /* something */;
int b = /* something */;
if( /* test */ ) {
/* ... */
}
a += b;
David Barina C/C++ tricks April 13, 2018 31 / 59
Integer overflow
C
#include <limits.h>
CHAR_MIN , SHRT_MIN , INT_MIN , LONG_MIN
CHAR_MAX , SHRT_MAX , INT_MAX , LONG_MAX
C++
#include <limits >
std:: numeric_limits <T>:: min()
std:: numeric_limits <T>:: max()
David Barina C/C++ tricks April 13, 2018 32 / 59
Integer overflow
int a = /* something */;
int b = /* something */;
addition ‘a + b‘
if( (b > 0) && (a > INT_MAX - b) )
/* would overflow */;
if( (b < 0) && (a < INT_MIN - b) )
/* would overflow */;
David Barina C/C++ tricks April 13, 2018 33 / 59
Integer overflow
int a = /* something */;
int b = /* something */;
subtraction ‘a - b‘
if( (b < 0) && (a > INT_MAX + b) )
/* would overflow */;
if( (b > 0) && (a < INT_MIN + b) )
/* would overflow */;
David Barina C/C++ tricks April 13, 2018 34 / 59
Integer overflow
int a = /* something */;
int b = /* something */;
multiplication ‘a * b‘
if( (b != 0) && (a > INT_MAX / b) )
/* would overflow */;
if( (b != 0) && (a < INT_MIN / b) )
/* would overflow */;
David Barina C/C++ tricks April 13, 2018 35 / 59
Integer overflow
int a = /* something */;
int b = /* something */;
multiplication ‘a * b‘
if( (b != 0) && (a > INT_MAX / b) )
/* would overflow */;
if( (b != 0) && (a < INT_MIN / b) )
/* would overflow */;
if( (a == -1) && (b == INT_MIN) )
/* would overflow */;
if( (b == -1) && (a == INT_MIN) )
/* would overflow */;
David Barina C/C++ tricks April 13, 2018 35 / 59
Integer overflow
int a = /* something */;
int b = /* something */;
division ‘a / b‘
if( (b == -1) && (a == INT_MIN) )
/* would overflow */;
David Barina C/C++ tricks April 13, 2018 36 / 59
Implicit type conversion
int a = 5;
int b = a; /* <--- */
David Barina C/C++ tricks April 13, 2018 37 / 59
Implicit type conversion
int a = 5;
int b = a; /* nothing interesting */
David Barina C/C++ tricks April 13, 2018 38 / 59
Implicit type conversion
char a = 5;
int b = a; /* <--- */
David Barina C/C++ tricks April 13, 2018 39 / 59
Implicit type conversion
char a = 5;
int b = a; /* implicit type conversion */
David Barina C/C++ tricks April 13, 2018 40 / 59
Implicit type conversion
int a = 5;
char b = a; /* implicit type conversion */
David Barina C/C++ tricks April 13, 2018 41 / 59
Implicit type conversion
int a = 300;
char b = a; /* alter a value */
David Barina C/C++ tricks April 13, 2018 42 / 59
Implicit type conversion
int i = -1;
unsigned int u = i; /* change the sign */
David Barina C/C++ tricks April 13, 2018 43 / 59
Implicit type conversion
-Wconversion
warning: conversion to ‘int’ from ‘long int’
may alter its value
warning: conversion to ‘unsigned char’ from ‘int’
may alter its value
-Wsign-conversion
warning: negative integer implicitly converted
to unsigned type
warning: conversion to ‘unsigned int’ from ‘int’
may change the sign of the result
David Barina C/C++ tricks April 13, 2018 44 / 59
Explicit type conversion (cast notation)
int a = 5;
char b = (char)a; /* no warning */
std:: cout << +b << std:: endl; // 5
David Barina C/C++ tricks April 13, 2018 45 / 59
Explicit type conversion (conversion operator)
int a = 5;
char b = static_cast <char >(a);
std:: cout << +b << std:: endl; // 5
David Barina C/C++ tricks April 13, 2018 46 / 59
Explicit type conversion (cast notation)
int a = 5;
double *b = (double *)&a; /* no warning */
std:: cout << *b << std:: endl; // 2.47033e -323
David Barina C/C++ tricks April 13, 2018 47 / 59
Explicit type conversion (conversion operator)
int a = 5;
double *b = static_cast <double *>&a;
error: invalid static_cast from type ‘int*’
to type ‘double*’
David Barina C/C++ tricks April 13, 2018 48 / 59
Explicit type conversion (conversion operator)
int a = 5;
double *b = reinterpret_cast <double *>(&a);
std:: cout << *b << std:: endl; // 2.47033e -323
David Barina C/C++ tricks April 13, 2018 49 / 59
Explicit type conversion
( new_type ) expression
const_cast<new_type>(expression)
static_cast<new_type>(expression)
static_cast followed by const_cast
reinterpret_cast<new_type>(expression)
reinterpret_cast followed by const_cast
David Barina C/C++ tricks April 13, 2018 50 / 59
Explicit type conversion (cast notation)
-Wold-style-cast
warning: use of old-style cast
David Barina C/C++ tricks April 13, 2018 51 / 59
Initializer lists
class A {
int i;
public:
A() { i = 0; } // default
A(int i_) { i = i_; } // init
A& operator =(int i_) { i = i_; } // init
};
class B {
A a;
public:
B() { a = 3; } // default , init
};
David Barina C/C++ tricks April 13, 2018 52 / 59
Initializer lists
class A {
int i;
public:
A() { i = 0; } // default
A(int i_) { i = i_; } // init
A& operator =(int i_) { i = i_; } // init
};
class B {
A a;
public:
B() : a(3) {} // init
};
David Barina C/C++ tricks April 13, 2018 53 / 59
const member
class A {
public:
const int i;
A(int i_) { i = i_; }
};
error: assignment of read-only member ‘A::i’
David Barina C/C++ tricks April 13, 2018 54 / 59
const member
class A {
public:
const int i;
A(int i_) : i(i_) {}
};
David Barina C/C++ tricks April 13, 2018 55 / 59
const member
class A {
public:
const int i;
A(int i_) : i(i_) {}
A& operator =( const A& a) {
i = a.i;
return *this;
}
};
error: assignment of read-only member ‘A::i’
David Barina C/C++ tricks April 13, 2018 56 / 59
const member
class A {
public:
const int i;
A(int i_) : i(i_) {}
A& operator =( const A& a) {
return *new(this) A(a);
}
};
A a(3);
a = A(4);
std:: cout << a.i << std:: endl; /* UB */
David Barina C/C++ tricks April 13, 2018 57 / 59
const member
class A {
public:
const int i;
A(int i_) : i(i_) {}
A& operator =( const A& a) {
return *new(this) A(a);
}
};
A a(3);
std:: cout << (a = A(4)).i << std:: endl;
David Barina C/C++ tricks April 13, 2018 58 / 59
const member (C++17)
class A {
public:
const int i;
A(int i_) : i(i_) {}
A& operator =( const A& a) {
return *new(this) A(a);
}
};
A a(3);
a = A(4);
std:: cout << std:: launder (&a)->i << std:: endl;
David Barina C/C++ tricks April 13, 2018 59 / 59

More Related Content

Similar to C/C++ tricks

2. Data, Operators, IO (5).ppt
2. Data, Operators, IO (5).ppt2. Data, Operators, IO (5).ppt
2. Data, Operators, IO (5).pptElisée Ndjabu
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 FeaturesJan Rüegg
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, iohtaitk
 
2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt2. Data, Operators, IO.ppt
2. Data, Operators, IO.pptswateerawat06
 
CGo for fun and profit
CGo for fun and profitCGo for fun and profit
CGo for fun and profitLiz Frost
 
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjb
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjbpointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjb
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjbTUSHARGAURAV11
 
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjb
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjbpointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjb
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjbTUSHARGAURAV11
 
C++ lab assignment
C++ lab assignmentC++ lab assignment
C++ lab assignmentSaket Pathak
 
Whats new in ES2019
Whats new in ES2019Whats new in ES2019
Whats new in ES2019chayanikaa
 
Basics of C programming - day 2
Basics of C programming - day 2Basics of C programming - day 2
Basics of C programming - day 2Ajay Khatri
 
#OOP_D_ITS - 3rd - Migration From C To C++
#OOP_D_ITS - 3rd - Migration From C To C++#OOP_D_ITS - 3rd - Migration From C To C++
#OOP_D_ITS - 3rd - Migration From C To C++Hadziq Fabroyir
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
Eta lang Beauty And The Beast
Eta lang Beauty And The Beast Eta lang Beauty And The Beast
Eta lang Beauty And The Beast Jarek Ratajski
 

Similar to C/C++ tricks (20)

2. Data, Operators, IO (5).ppt
2. Data, Operators, IO (5).ppt2. Data, Operators, IO (5).ppt
2. Data, Operators, IO (5).ppt
 
operators.ppt
operators.pptoperators.ppt
operators.ppt
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, io
 
2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt
 
C++17 now
C++17 nowC++17 now
C++17 now
 
CGo for fun and profit
CGo for fun and profitCGo for fun and profit
CGo for fun and profit
 
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjb
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjbpointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjb
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjb
 
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjb
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjbpointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjb
pointer.ppt hfkogfhkigfvjjgdsyhhgfdfghjb
 
pointers CP Lecture.ppt
pointers CP Lecture.pptpointers CP Lecture.ppt
pointers CP Lecture.ppt
 
C++ lab assignment
C++ lab assignmentC++ lab assignment
C++ lab assignment
 
Whats new in ES2019
Whats new in ES2019Whats new in ES2019
Whats new in ES2019
 
Benchmark it
Benchmark itBenchmark it
Benchmark it
 
Buggi (2).pdf
Buggi (2).pdfBuggi (2).pdf
Buggi (2).pdf
 
Basics of C programming - day 2
Basics of C programming - day 2Basics of C programming - day 2
Basics of C programming - day 2
 
C# 8 and Beyond
C# 8 and BeyondC# 8 and Beyond
C# 8 and Beyond
 
#OOP_D_ITS - 3rd - Migration From C To C++
#OOP_D_ITS - 3rd - Migration From C To C++#OOP_D_ITS - 3rd - Migration From C To C++
#OOP_D_ITS - 3rd - Migration From C To C++
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Eta lang Beauty And The Beast
Eta lang Beauty And The Beast Eta lang Beauty And The Beast
Eta lang Beauty And The Beast
 
Lambda expressions in C++
Lambda expressions in C++Lambda expressions in C++
Lambda expressions in C++
 

More from David Bařina

Lossy Light Field Compression
Lossy Light Field CompressionLossy Light Field Compression
Lossy Light Field CompressionDavid Bařina
 
Mathematical curiosities
Mathematical curiositiesMathematical curiosities
Mathematical curiositiesDavid Bařina
 
New Transforms for JPEG Format
New Transforms for JPEG FormatNew Transforms for JPEG Format
New Transforms for JPEG FormatDavid Bařina
 
Discrete Wavelet Transforms on Parallel Architectures
Discrete Wavelet Transforms on Parallel ArchitecturesDiscrete Wavelet Transforms on Parallel Architectures
Discrete Wavelet Transforms on Parallel ArchitecturesDavid Bařina
 
Parallel Implementation of the 2-D Discrete Wavelet Transform
Parallel Implementation of the 2-D Discrete Wavelet TransformParallel Implementation of the 2-D Discrete Wavelet Transform
Parallel Implementation of the 2-D Discrete Wavelet TransformDavid Bařina
 
Parallel Wavelet Schemes for Images
Parallel Wavelet Schemes for ImagesParallel Wavelet Schemes for Images
Parallel Wavelet Schemes for ImagesDavid Bařina
 
Single-Loop Software Architecture for JPEG 2000
Single-Loop Software Architecture for JPEG 2000Single-Loop Software Architecture for JPEG 2000
Single-Loop Software Architecture for JPEG 2000David Bařina
 
Lifting Scheme Cores for Wavelet Transform
Lifting Scheme Cores for Wavelet TransformLifting Scheme Cores for Wavelet Transform
Lifting Scheme Cores for Wavelet TransformDavid Bařina
 
Real-Time 3-D Wavelet Lifting
Real-Time 3-D Wavelet LiftingReal-Time 3-D Wavelet Lifting
Real-Time 3-D Wavelet LiftingDavid Bařina
 
IIR aproximace Gaussovy funkce
IIR aproximace Gaussovy funkceIIR aproximace Gaussovy funkce
IIR aproximace Gaussovy funkceDavid Bařina
 
Akcelerace DWT pomocí SIMD
Akcelerace DWT pomocí SIMDAkcelerace DWT pomocí SIMD
Akcelerace DWT pomocí SIMDDavid Bařina
 
Wavelet Lifting on Application Specific Vector Processor
Wavelet Lifting on Application Specific Vector ProcessorWavelet Lifting on Application Specific Vector Processor
Wavelet Lifting on Application Specific Vector ProcessorDavid Bařina
 
Bit Twiddling Hacks: Integers
Bit Twiddling Hacks: IntegersBit Twiddling Hacks: Integers
Bit Twiddling Hacks: IntegersDavid Bařina
 
Fixed-point arithmetic
Fixed-point arithmeticFixed-point arithmetic
Fixed-point arithmeticDavid Bařina
 

More from David Bařina (20)

CCSDS 122.0
CCSDS 122.0CCSDS 122.0
CCSDS 122.0
 
Lossy Light Field Compression
Lossy Light Field CompressionLossy Light Field Compression
Lossy Light Field Compression
 
Mathematical curiosities
Mathematical curiositiesMathematical curiosities
Mathematical curiosities
 
New Transforms for JPEG Format
New Transforms for JPEG FormatNew Transforms for JPEG Format
New Transforms for JPEG Format
 
JPEG
JPEGJPEG
JPEG
 
Discrete Wavelet Transforms on Parallel Architectures
Discrete Wavelet Transforms on Parallel ArchitecturesDiscrete Wavelet Transforms on Parallel Architectures
Discrete Wavelet Transforms on Parallel Architectures
 
Parallel Implementation of the 2-D Discrete Wavelet Transform
Parallel Implementation of the 2-D Discrete Wavelet TransformParallel Implementation of the 2-D Discrete Wavelet Transform
Parallel Implementation of the 2-D Discrete Wavelet Transform
 
Parallel Wavelet Schemes for Images
Parallel Wavelet Schemes for ImagesParallel Wavelet Schemes for Images
Parallel Wavelet Schemes for Images
 
Single-Loop Software Architecture for JPEG 2000
Single-Loop Software Architecture for JPEG 2000Single-Loop Software Architecture for JPEG 2000
Single-Loop Software Architecture for JPEG 2000
 
Lifting Scheme Cores for Wavelet Transform
Lifting Scheme Cores for Wavelet TransformLifting Scheme Cores for Wavelet Transform
Lifting Scheme Cores for Wavelet Transform
 
Real-Time 3-D Wavelet Lifting
Real-Time 3-D Wavelet LiftingReal-Time 3-D Wavelet Lifting
Real-Time 3-D Wavelet Lifting
 
Wavelet News
Wavelet NewsWavelet News
Wavelet News
 
IIR aproximace Gaussovy funkce
IIR aproximace Gaussovy funkceIIR aproximace Gaussovy funkce
IIR aproximace Gaussovy funkce
 
Akcelerace DWT pomocí SIMD
Akcelerace DWT pomocí SIMDAkcelerace DWT pomocí SIMD
Akcelerace DWT pomocí SIMD
 
Wavelet Lifting on Application Specific Vector Processor
Wavelet Lifting on Application Specific Vector ProcessorWavelet Lifting on Application Specific Vector Processor
Wavelet Lifting on Application Specific Vector Processor
 
GStreamer
GStreamerGStreamer
GStreamer
 
FFmpeg
FFmpegFFmpeg
FFmpeg
 
Bit Twiddling Hacks: Integers
Bit Twiddling Hacks: IntegersBit Twiddling Hacks: Integers
Bit Twiddling Hacks: Integers
 
Fixed-point arithmetic
Fixed-point arithmeticFixed-point arithmetic
Fixed-point arithmetic
 
Wavelets @ CPU
Wavelets @ CPUWavelets @ CPU
Wavelets @ CPU
 

Recently uploaded

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 

Recently uploaded (20)

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 

C/C++ tricks

  • 1. C/C++ tricks David Barina April 13, 2018 David Barina C/C++ tricks April 13, 2018 1 / 59
  • 2. Duff’s device switch (count % 8) { case 0: do { *to = *from ++; case 7: *to = *from ++; case 6: *to = *from ++; case 5: *to = *from ++; case 4: *to = *from ++; case 3: *to = *from ++; case 2: *to = *from ++; case 1: *to = *from ++; } while (( count -= 8) > 0); } David Barina C/C++ tricks April 13, 2018 2 / 59
  • 3. [] operator const char *a = "0123456789 abcdef"; int i = ...; char digit = a[i]; char digit = *(a+i); David Barina C/C++ tricks April 13, 2018 3 / 59
  • 4. [] operator const char *a = "0123456789 abcdef"; int i = ...; char digit = a[i]; char digit = *(a+i); char digit = i[a]; David Barina C/C++ tricks April 13, 2018 4 / 59
  • 5. Swap algorithm void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void swap(int *a, int *b) { *a ^= *b; *b ^= *a; *a ^= *b; } David Barina C/C++ tricks April 13, 2018 5 / 59
  • 6. --> operator int x = 10; while( x --> 0 ) while( 0 <-- x ) while( 0 <---- x ) David Barina C/C++ tricks April 13, 2018 6 / 59
  • 7. Catching exceptions in initializer lists struct A { A() : b() { ... } B b; }; A() : b() { try { ... } catch (...) { ... } } David Barina C/C++ tricks April 13, 2018 7 / 59
  • 8. Catching exceptions in initializer lists struct A { A() : b() { ... } B b; }; A() try : b() { ... } catch (...) { ... } David Barina C/C++ tricks April 13, 2018 8 / 59
  • 9. Namespace aliases namespace foo { namespace bar { namespace baz { int qux = 42; } } } namespace fbz = foo::bar::baz; std:: cout << fbz::qux << ’n’; David Barina C/C++ tricks April 13, 2018 9 / 59
  • 10. Namespace aliases #if THREADS_ARE_SUPPORTED_ON_THE_PLATFORM namespace lib = project ::lib:: impl_with_threads ; #else namespace lib = project ::lib:: impl_wout_threads ; #endif David Barina C/C++ tricks April 13, 2018 10 / 59
  • 11. Storage class specifiers typedef int type; int typedef type; // static , extern David Barina C/C++ tricks April 13, 2018 11 / 59
  • 12. Integer overflow for(char c = 100; c > 0; c++) printf("%in", (int)c); David Barina C/C++ tricks April 13, 2018 12 / 59
  • 13. Integer promotion char c = ’X’; cout << c; David Barina C/C++ tricks April 13, 2018 13 / 59
  • 14. Integer promotion char c = ’X’; cout << c; cout << +c; David Barina C/C++ tricks April 13, 2018 14 / 59
  • 15. Polyglot $CC -std=c90 -pedantic -Wall -Wextra prog.c && ./a.out I am compiled with C90 $CC -std=c99 -pedantic -Wall -Wextra prog.c && ./a.out I am compiled with C99 $CC -std=c11 -pedantic -Wall -Wextra prog.c && ./a.out I am compiled with C11 or newer $CXX -std=c++98 -pedantic -Wall -Wextra prog.c && ./a.out I am compiled with C++03 or older $CXX -std=c++03 -pedantic -Wall -Wextra prog.c && ./a.out I am compiled with C++03 or older $CXX -std=c++11 -pedantic -Wall -Wextra prog.c && ./a.out I am compiled with C++11 or newer David Barina C/C++ tricks April 13, 2018 15 / 59
  • 16. Polyglot if( sizeof(’a’) == sizeof(char) ) { // compiled with C++ } else { // compiled with C } David Barina C/C++ tricks April 13, 2018 16 / 59
  • 17. Polyglot #define R(U) sizeof(U"a"[0]) if( R("") == 4 ) { // C++11 or newer } else { // C++03 or older } David Barina C/C++ tricks April 13, 2018 17 / 59
  • 18. Polyglot if( 2 // **/2 == 2 ) { if( R("") == 4 ) { // C11 or newer } else { // C99 } } else { // C90 } David Barina C/C++ tricks April 13, 2018 18 / 59
  • 19. Named loops David Barina C/C++ tricks April 13, 2018 19 / 59
  • 20. Named loops outer: for( ... ) { inner: for( ... ) { ... goto outer; } } David Barina C/C++ tricks April 13, 2018 20 / 59
  • 21. Named loops for( ... ) { for( ... ) { ... goto after; } } after :; David Barina C/C++ tricks April 13, 2018 21 / 59
  • 22. Named loops if( 0 ) after :; else for( ... ) { for( ... ) { ... goto after; } } David Barina C/C++ tricks April 13, 2018 22 / 59
  • 23. Named loops [](){ for( ... ) { for( ... ) { ... return; } } }(); David Barina C/C++ tricks April 13, 2018 23 / 59
  • 24. Copy-and-swap class dumb_array { public: dumb_array(std:: size_t size = 0); dumb_array(const dumb_array& other ); ~dumb_array (); private: std:: size_t mSize; int* mArray; }; David Barina C/C++ tricks April 13, 2018 24 / 59
  • 25. Copy-and-swap dumb_array& operator =( const dumb_array& other) { if (this != &other) // (1) { delete [] mArray; // (2) mArray = nullptr; // (2) mSize = other.mSize; // (3) mArray = mSize ? new int[mSize] : nullptr; // (3) std:: copy(other.mArray , other.mArray + mSize , mArray ); // (3) } return *this; } David Barina C/C++ tricks April 13, 2018 25 / 59
  • 26. Copy-and-swap friend void swap(dumb_array& first , dumb_array& second) // nothrow { using std:: swap; swap(first.mSize , second.mSize ); swap(first.mArray , second.mArray ); } dumb_array& operator =( dumb_array other) // (1) { swap (*this , other ); // (2) return *this; } David Barina C/C++ tricks April 13, 2018 26 / 59
  • 27. Member call on null pointer class A { int x; public: void foo() { std:: cout << "foo" << std:: endl; x = 0; } }; int main () { A *a = 0; a->foo (); } David Barina C/C++ tricks April 13, 2018 27 / 59
  • 28. Member call on null pointer class A { int x; public: void foo() { std:: cout << "foo" << std:: endl; x = 0; } }; int main () { A *a = 0; a->foo (); } foo Neopr´avnˇen´y pˇr´ıstup do pamˇeti (SIGSEGV) David Barina C/C++ tricks April 13, 2018 27 / 59
  • 29. Member call on null pointer class A { int x; public: void bar() { std:: cout << "bar" << std:: endl; } }; int main () { A *a = 0; a->bar (); } David Barina C/C++ tricks April 13, 2018 28 / 59
  • 30. Member call on null pointer class A { int x; public: void bar() { std:: cout << "bar" << std:: endl; } }; int main () { A *a = 0; a->bar (); } bar David Barina C/C++ tricks April 13, 2018 28 / 59
  • 31. Integer overflow int a = /* something */; int b = /* something */; a += b; if( a < 0 ) { /* ... */ } David Barina C/C++ tricks April 13, 2018 29 / 59
  • 32. Integer overflow int a = /* something */; int b = /* something */; a += b; /* UB */ if( a < 0 ) { /* unreliable test */ /* ... */ } David Barina C/C++ tricks April 13, 2018 30 / 59
  • 33. Integer overflow int a = /* something */; int b = /* something */; if( /* test */ ) { /* ... */ } a += b; David Barina C/C++ tricks April 13, 2018 31 / 59
  • 34. Integer overflow C #include <limits.h> CHAR_MIN , SHRT_MIN , INT_MIN , LONG_MIN CHAR_MAX , SHRT_MAX , INT_MAX , LONG_MAX C++ #include <limits > std:: numeric_limits <T>:: min() std:: numeric_limits <T>:: max() David Barina C/C++ tricks April 13, 2018 32 / 59
  • 35. Integer overflow int a = /* something */; int b = /* something */; addition ‘a + b‘ if( (b > 0) && (a > INT_MAX - b) ) /* would overflow */; if( (b < 0) && (a < INT_MIN - b) ) /* would overflow */; David Barina C/C++ tricks April 13, 2018 33 / 59
  • 36. Integer overflow int a = /* something */; int b = /* something */; subtraction ‘a - b‘ if( (b < 0) && (a > INT_MAX + b) ) /* would overflow */; if( (b > 0) && (a < INT_MIN + b) ) /* would overflow */; David Barina C/C++ tricks April 13, 2018 34 / 59
  • 37. Integer overflow int a = /* something */; int b = /* something */; multiplication ‘a * b‘ if( (b != 0) && (a > INT_MAX / b) ) /* would overflow */; if( (b != 0) && (a < INT_MIN / b) ) /* would overflow */; David Barina C/C++ tricks April 13, 2018 35 / 59
  • 38. Integer overflow int a = /* something */; int b = /* something */; multiplication ‘a * b‘ if( (b != 0) && (a > INT_MAX / b) ) /* would overflow */; if( (b != 0) && (a < INT_MIN / b) ) /* would overflow */; if( (a == -1) && (b == INT_MIN) ) /* would overflow */; if( (b == -1) && (a == INT_MIN) ) /* would overflow */; David Barina C/C++ tricks April 13, 2018 35 / 59
  • 39. Integer overflow int a = /* something */; int b = /* something */; division ‘a / b‘ if( (b == -1) && (a == INT_MIN) ) /* would overflow */; David Barina C/C++ tricks April 13, 2018 36 / 59
  • 40. Implicit type conversion int a = 5; int b = a; /* <--- */ David Barina C/C++ tricks April 13, 2018 37 / 59
  • 41. Implicit type conversion int a = 5; int b = a; /* nothing interesting */ David Barina C/C++ tricks April 13, 2018 38 / 59
  • 42. Implicit type conversion char a = 5; int b = a; /* <--- */ David Barina C/C++ tricks April 13, 2018 39 / 59
  • 43. Implicit type conversion char a = 5; int b = a; /* implicit type conversion */ David Barina C/C++ tricks April 13, 2018 40 / 59
  • 44. Implicit type conversion int a = 5; char b = a; /* implicit type conversion */ David Barina C/C++ tricks April 13, 2018 41 / 59
  • 45. Implicit type conversion int a = 300; char b = a; /* alter a value */ David Barina C/C++ tricks April 13, 2018 42 / 59
  • 46. Implicit type conversion int i = -1; unsigned int u = i; /* change the sign */ David Barina C/C++ tricks April 13, 2018 43 / 59
  • 47. Implicit type conversion -Wconversion warning: conversion to ‘int’ from ‘long int’ may alter its value warning: conversion to ‘unsigned char’ from ‘int’ may alter its value -Wsign-conversion warning: negative integer implicitly converted to unsigned type warning: conversion to ‘unsigned int’ from ‘int’ may change the sign of the result David Barina C/C++ tricks April 13, 2018 44 / 59
  • 48. Explicit type conversion (cast notation) int a = 5; char b = (char)a; /* no warning */ std:: cout << +b << std:: endl; // 5 David Barina C/C++ tricks April 13, 2018 45 / 59
  • 49. Explicit type conversion (conversion operator) int a = 5; char b = static_cast <char >(a); std:: cout << +b << std:: endl; // 5 David Barina C/C++ tricks April 13, 2018 46 / 59
  • 50. Explicit type conversion (cast notation) int a = 5; double *b = (double *)&a; /* no warning */ std:: cout << *b << std:: endl; // 2.47033e -323 David Barina C/C++ tricks April 13, 2018 47 / 59
  • 51. Explicit type conversion (conversion operator) int a = 5; double *b = static_cast <double *>&a; error: invalid static_cast from type ‘int*’ to type ‘double*’ David Barina C/C++ tricks April 13, 2018 48 / 59
  • 52. Explicit type conversion (conversion operator) int a = 5; double *b = reinterpret_cast <double *>(&a); std:: cout << *b << std:: endl; // 2.47033e -323 David Barina C/C++ tricks April 13, 2018 49 / 59
  • 53. Explicit type conversion ( new_type ) expression const_cast<new_type>(expression) static_cast<new_type>(expression) static_cast followed by const_cast reinterpret_cast<new_type>(expression) reinterpret_cast followed by const_cast David Barina C/C++ tricks April 13, 2018 50 / 59
  • 54. Explicit type conversion (cast notation) -Wold-style-cast warning: use of old-style cast David Barina C/C++ tricks April 13, 2018 51 / 59
  • 55. Initializer lists class A { int i; public: A() { i = 0; } // default A(int i_) { i = i_; } // init A& operator =(int i_) { i = i_; } // init }; class B { A a; public: B() { a = 3; } // default , init }; David Barina C/C++ tricks April 13, 2018 52 / 59
  • 56. Initializer lists class A { int i; public: A() { i = 0; } // default A(int i_) { i = i_; } // init A& operator =(int i_) { i = i_; } // init }; class B { A a; public: B() : a(3) {} // init }; David Barina C/C++ tricks April 13, 2018 53 / 59
  • 57. const member class A { public: const int i; A(int i_) { i = i_; } }; error: assignment of read-only member ‘A::i’ David Barina C/C++ tricks April 13, 2018 54 / 59
  • 58. const member class A { public: const int i; A(int i_) : i(i_) {} }; David Barina C/C++ tricks April 13, 2018 55 / 59
  • 59. const member class A { public: const int i; A(int i_) : i(i_) {} A& operator =( const A& a) { i = a.i; return *this; } }; error: assignment of read-only member ‘A::i’ David Barina C/C++ tricks April 13, 2018 56 / 59
  • 60. const member class A { public: const int i; A(int i_) : i(i_) {} A& operator =( const A& a) { return *new(this) A(a); } }; A a(3); a = A(4); std:: cout << a.i << std:: endl; /* UB */ David Barina C/C++ tricks April 13, 2018 57 / 59
  • 61. const member class A { public: const int i; A(int i_) : i(i_) {} A& operator =( const A& a) { return *new(this) A(a); } }; A a(3); std:: cout << (a = A(4)).i << std:: endl; David Barina C/C++ tricks April 13, 2018 58 / 59
  • 62. const member (C++17) class A { public: const int i; A(int i_) : i(i_) {} A& operator =( const A& a) { return *new(this) A(a); } }; A a(3); a = A(4); std:: cout << std:: launder (&a)->i << std:: endl; David Barina C/C++ tricks April 13, 2018 59 / 59