Nov 2, 2018

[CppCon 2018] The Nightmare of Initialization in C++ - Nicolai Josuttis


Interestingly RVO (Return Value Optimization) has become a hot topic in C++17, not only Nicolai talks about it, Arthur O'Dwyer also has a talk in CppCon2018 talking about RVO.

Years back when I first read of RVO is, again, from the classic book written by Stanley B. Lippman, Inside the C++ Object Model. RVO used to be an option for compiler, but now is mandated in C++17.


Initialization in C++
Well, you could see this mocking video about C++'s initialization on the web :-)


RVO works for constructor
// RVO works for constructor.
auto a = std::atomic<int>{9};
auto r = std::array{};



C++17's prvalue:
prvalue can temporary materialization conversion' to
xvalue.


Does compiler always warns while doing a narrow type
conversion?
Not really for template:
[C++11/14] constant expression value can convert to smaller size data structure


C++17 relaxed Enumeration Initialization
Initialize enumerations with integral values:

enum class Test { a, b};
Test te1{0}; // ok in C++17

enum Int : unsigned long long{};
Int ie1{42}; // ok in C++17

enum Flag {b1=1, b2=2};
Flag f3{0}; // error!

std::byte b{0b111'111}; // ok in C++17

Rule of thumb:
Make sure either both default constructor and one argument/initialization list constructor explicit or both non-explicit.
If not:
vector<int> v1 = {1 , 2}; // ok
vector<int> v2 = {1}; // ok
vector<int> v2 = {}; // error! in C++11, fixed in C++14


Aggregates:
  • C
    • Structs or arrays (types for multiple members, not union)
  • C++98/03: class or array with:
    • no user-declared constructors
    • no private or protected non-static data members
    • no base classes
    • no virtual functions
  • C++11/14: class or array with:
    • no user-provided constructors
    • no private or protected non-static data members
    • no base classes
    • no virtual functions
  • C++17: class or array with:
    • no user-provided, explicit, or inherited constructors
    • no private or protected non-static data members
    • no virtual, private, or protected base classes
    • no virtual functions
  • std::array<> is an aggregate,
    i.e without initialize value is an UB.
Reference:
[golang][c++] padding


assert:
Beware about comma, since assert is a macro.
This is mentioned in Davide Di Gennaro's
Advanced Metaprogramming in Classic C++
assert( c == std::complex(0,0)); // ok
assert( c == std::complex{0,0}); // error
assert(( c == std::complex{0,0})); // ok



Reference:

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.