Presentation: “What`s new in VC++2015?” by Marc Gregoire

advertisement
What's new in Microsoft
Visual C++ 2015 Preview
Marc Grégoire
marc.gregoire@nuonsoft.com
http://www.nuonsoft.com/
http://www.nuonsoft.com/blog/
December 17th 2014
Agenda




C++11, C++14, C++17
Productivity Improvements
Improved Performance
C++ Cross-Platform Mobile Dev
C++11, C++14, C++17
Increased standard compliancy
C++11 Core Language Features

New or updated C++11 core language features













ref-qualifiers
Partial support for constexpr
Inheriting constructors
char16_t and char32_t
Unicode string literals
User-defined literals
Full defaulted and deleted functions support (partial in VC++2013)
Extended sizeof()
noexcept
Inline namespaces
Full Rvalue references compliant (partial VC++2013)
Full alignment support (partial in VC++2013)
Unrestricted unions
ref-qualifiers

rvalue references are well-known for function
parameters, example:
 void

foo(Bar&& bar);
How to apply rvalue reference to *this?
class Foo {
};
void f1() const;
// *this is const
void f2() &;
// *this is an lvalue
void f3() &&;
// *this is an rvalue
ref-qualifiers – Contrived Example
class BigObject {};
class BigObjectFactory {
public:
BigObject Get() {
return m_bigObject;
}
private:
BigObject m_bigObject;
};
BigObjectFactory aFactory;
BigObject obj = aFactory.Get();
ref-qualifiers – Contrived Example

But what with this:
BigObject obj = BigObjectFactory().Get();


The factory is a temporary object, but BigObject is
still copied because *this is not an rvalue-reference
Solution:
 Make
BigObject moveable
 Overload Get() for an rvalue-reference *this
ref-qualifiers – Contrived Example
class BigObject {};
class BigObjectFactory {
public:
BigObject Get() const & {
// *this is an lvalue
return m_bigObject;
// Deep copy
}
BigObject Get() && {
// *this is an rvalue
return std::move(m_bigObject); // move
}
private:
BigObjectFactory myFactory;
BigObject m_bigObject;
BigObject o1 = myFactory.Get();
// Deep copy
};
BigObject o2 = BigObjectFactory().Get();// Move
constexpr


Constant expressions
Simple example
static constexpr size_t FACTOR = 2;
constexpr size_t CalculateArraySize(size_t base)
{
return base * FACTOR;
}
...
double arr[CalculateArraySize(123)];
Inheriting constructors
class Base
{
public:
Base(int data) : m_data(data) {}
private:
int m_data;
};
class Derived : Base
{
public:
Derived(const std::string& msg) : Base(1), m_msg(msg) {}
private:
std::string m_msg;
};
...
Base b1(123);
// OK
Derived d1("Message"); // OK
Derived d2(456);
// NOT OK
Inheriting Constructors
class Base
{
public:
Base(int data) : m_data(data) {}
private:
int m_data;
};
class Derived : Base
{
public:
using Base::Base;
Derived(const std::string& msg) : Base(1), m_msg(msg) {}
private:
std::string m_msg;
};
...
Derived d2(456);
// OK
char16_t and char32_t

Existing character types:
 char:
only 8 bits
 wchar_t: compiler-dependent size, not specified by
C++ standard!  hard to use for platform independent
code

New character types: char16_t and char32_t
char16_t and char32_t

In total 4 character types:
 char:
stores 8 bits; can be used to store ASCII, or as
building block for UTF-8 encoded Unicode characters
 char16_t: stores at least 16 bits; building block for UTF16 encoded Unicode characters
 char32_t: stores at least 32 bits; building block for UTF32 encoded Unicode characters
 wchar_t: stores a wide character of a compiler
dependent size and encoding
char16_t and char32_t

A compiler can define the following new
preprocessor defines:
 __STDC_UTF_32__:
If defined then char32_t represents a
UTF-32 encoding, otherwise it has a compiler
dependent encoding.
 __STDC_UTF_16__: If defined then char16_t represents a
UTF-16 encoding, otherwise it has a compiler
dependent encoding.

Both not defined in VC++2015 Preview
char16_t and char32_t

New std::basic_string specializations:
 typedef
basic_string<char> string;
 typedef basic_string<wchar_t> wstring;
 typedef basic_string<char16_t> u16string;
 typedef basic_string<char32_t> u32string;
char16_t and char32_t



Unfortunately, support for char16_t and char32_t
stops here
No I/O stream classes support these new types
No version of cout/cin/… for these types
Unicode String Literals

New string literals:
 L:
A wchar_t string literal with a compiler-dependent
encoding
 u8: A char string literal with UTF-8 encoding
 u: A char16_t string literal, which can be UTF-16 if
__STDC_UTF_16__ is defined by the compiler
 U: A char32_t string literal, which can be UTF-32 if
__STDC_UTF_32__ is defined by the compiler
Unicode String Literals

All can be combined with the R prefix for raw string
literals:
const
const
const
const
char* s1 = u8R"(Raw UTF-8 encoded string literal)";
wchar_t* s2 = LR"(Raw wide string literal)";
char16_t* s3 = uR"(Raw char16_t string literal)";
char32_t* s4 = UR"(Raw char32_t string literal)";
User-Defined Literals

C++ has standard literals such as:
character
 "character array": zero-terminated array of
characters, C-style string
 3.14f: float floating point value
 0xabc: hexadecimal value
 'a':
User-Defined Literals


Start with _
Implemented in a literal operator:
 Raw
mode: op receives sequence of characters
 Cooked mode: op receives an interpreted type
 Example: literal 0x23
 Raw
mode op receives ‘0’, ‘x’, ‘2’, ‘3’
 Cooked mode op receives the integer 35
User-Defined Literals – Cooked Mode

Has 1 parameter to process numeric values
 Type
can be unsigned long long, long double, char,
wchar_t, char16_t or char32_t

or 2 parameters to process strings
a
character array
 the length of the character array
 example: (const char* str, size_t len)
User-Defined Literals – Cooked Mode

Example: cooked mode complex number literal
std::complex<double> operator"" _i(long double d)
{
return std::complex<double>(0, d);
}
std::complex<double> c1 = 9.634_i;
auto c2 = 1.23_i;
// type is std::complex<double>
User-Defined Literals – Cooked Mode

Example: cooked mode std::string literal
std::string operator"" _s(const char* str, size_t len)
{
return std::string(str, len);
}
std::string str1 = "Hello World"_s;
auto str2 = "Hello World"_s;
// type is std::string
auto str3 = "Hello World";
// type is const char*
User-Defined Literals – Raw Mode

Example: raw mode complex number literal
std::complex<double> operator"" _i(const char* p)
{
// Implementation omitted; it requires parsing the C-style
// string and converting it to a complex number.
}
Full Defaulted and Deleted Functions Support

=default


Ask the compiler to forcefully generate the default
implementation
Example:
class C
{
public:
C(int i) {}
C() = default;
};
Full Defaulted and Deleted Functions Support



=delete
 Forcefully delete an implementation
Error message states intent, better error message than making
it private without implementation
Example:
class C
{
public:
C() = delete;
C(const C& src) = delete;
C& operator=(const C& src) = delete;
};
C c;//error C2280:'C::C(void)': attempting to reference a deleted function
Full Defaulted and Deleted Functions Support


=delete can be used to disallow calling a function with a certain type
Example:
void foo(int i) { }
...
foo(123);
foo(1.23); // Compiles, but with warning

Disallow calling foo() with doubles by deleting a double overload of foo():
void foo(int i) { }
void foo(double d) = delete;
...
foo(123);
foo(1.23); // error C2280: 'void foo(double)' :
// attempting to reference a deleted function
Extended sizeof()


sizeof() on class members without an instance
Example:
class Bar {};
class Foo {
public:
Bar m_bar;
};
sizeof(Foo::m_bar);
noexcept

Double meaning:

noexcept to mark a function as non-throwing
void func1();
void func2() noexcept(expr);
void func3() noexcept;


// Can throw anything
// A constant expression returning a Boolean
//
true means func2 cannot throw
//
false means func2 can throw
// = noexcept(true)
If a noexcept-marked function does throw at runtime,
terminate() is called
Note that old exception specifications are deprecated since
C++11
noexcept



noexcept as an operator: noexcept(expr)
Example:
bool b1 = noexcept(2 + 3);
bool b2 = noexcept(throw 1);
// b1 = true
// b2 = false
void func1() { }
bool b3 = noexcept(func1());
// b3 = false
void func2() noexcept { }
bool b4 = noexcept(func2());
// b4 = true
Used by the standard library to decide between moving or
copying

Thus, mark your move ctor and move assignment operator noexcept
Inline Namespace


Intended for libraries to support versioning
Example:
// file V98.h:
namespace V98 {
void f(int);
}
// does something
// file V99.h:
inline namespace V99 {
void f(int);
// does something better than the V98 version
void f(double); // new feature
}
#include "MyLibrary.h"
using namespace MyLibrary;
// file MyLibrary.h:
namespace MyLibrary {
#include "V99.h"
#include "V98.h"
}
V98::f(1); // old version
V99::f(1); // new version
f(1);
// default version
C++11 Core Language Concurrency Features

New or updated C++11 core language
concurrency features
 quick_exit()
and at_quick_exit()
 Full support for thread-local storage (partial in
VC++2013)
 Magic statics
quick_exit() and at_quick_exit()

quick_exit() terminates application as follows:
 Calls
all functions registered with at_quick_exit()
 Terminates application


Except at_quick_exit() handlers, no other cleanup is
done
No destructors are called
Thread-Local Storage



Keyword: thread_local
Each thread gets its own instance
Example:
thread_local unsigned int data = 1;
Magic Statics




Thread-safe “Magic” statics
Static local variables are initialized in a thread-safe
way
No manual synchronization needed for
initialization
Using statics from multiple threads still requires
manual synchronization
Magic Statics

Example: simple thread-safe singleton:
static Singleton& GetInstance()
{
static Singleton theInstance;
return theInstance;
}
C++11 Core Language C99 Features

New or updated C++11 core language C99
features
 __func__
__func__

Standard way to get the name of a function
int _tmain(int argc, _TCHAR* argv[])
{
cout << __func__ << endl;
return 0;
}

Output:
wmain
C++14 Core Language Features

New or updated C++14 core language features
 Binary
literals
 auto and decltype(auto) return types
 Lambda capture expressions
 Generic lambdas
 Digit separators (will be in RTM)
 Sized deallocation (partial support)
Binary Literals
int value = 0b1111011; // = 123
auto and decltype(auto) Return Types
Both auto and decltype(auto) can be used to
let the compiler deduce the return type
 auto strips ref-qualifiers (lvalue and rvalue
references) and strips cv-qualifiers (const and
volatile)
 Decltype(auto) does not strip those

auto and decltype(auto) Return Types

Example: return type will be int
auto Foo(int i)
{
return i + 1;
}

Example: return type will be double
template<typename T>
auto Bar(const T& t)
{
return t * 2;
}
...
auto result = Bar<double>(1.2);
auto and decltype(auto) Return Types


Multiple return statements are allowed but all need
to be of exactly the same type
Following won’t compile
 returns
int and unsigned int
auto Foo(int i)
{
if (i > 1)
return 1;
else
return 2u;
}
auto and decltype(auto) Return Types


Recursion allowed but there must be a nonrecursive return before the recursive call
Correct:
 Wrong:
auto Foo(int i)
{
if (i == 0)
return 0;
else
return i + Foo(i - 1);
}
auto Foo(int i)
{
if (i > 0)
return i + Foo(i - 1);
else
return 0;
}
decltype(auto)

Quick reminder:
static const string message = "Test";
const string& Foo()
{
return message;
}
...
auto f1 = Foo();
decltype(Foo()) f2 = Foo();
decltype(auto) f3 = Foo();
 Type: string
 Type: const string&
 Type: const string&
auto and decltype(auto) Return Types
decltype(auto) as return type
 Example:

auto Foo1(const string& str)
{
return str;
}
decltype(auto) a = Foo1("abc");
decltype(auto) b = Foo2("abc");
decltype(auto) Foo2(const string& str)
{
return str;
}
 Return Type: string
 Return Type: const string&
Lambda Capture Expressions


Capture expressions to initialize lambda variables
Example:
float pi = 3.1415;
auto myLambda = [myCapture = "Pi: ", pi]{ std::cout << myCapture << pi; };
 Lambda
has 2 variables:
 myCapture:
a string (not from the enclosing scope) with
value “Pi: “
 pi: captured from the enclosing scope
Lambda Capture Expressions


Allow moving variables into the lambda
Example:
auto myPtr = std::make_unique<double>(3.1415);
auto myLambda = [p = std::move(myPtr)]{ std::cout << *p; };
 Lambda
 p:
has 1 variable:
a unique_ptr captured and moved from the enclosing
scope (could even be called myPtr)
Generic Lambdas

Lambda parameters can be declared as auto 
auto doubler = [](const auto& value){ return value * 2; };
...
vector<int> v1{ 1, 2, 3 };
transform(begin(v1), end(v1), begin(v1), doubler);
...
vector<double> v2{ 1.1, 2.2, 3.3 };
transform(begin(v2), end(v2), begin(v2), doubler);
Digit Separators (will be in RTM)


Single quote character
Example:
int number1 = 23'456'789;
// The number 23456789
float number2 = 0.123'456f;
// The number 0.123456
C++14 Library Features

New or updated C++14 library features
Standard user-defined literals
 Null forward iterators
 quoted()
 Heterogeneous associative lookup
 Compile-time integer sequences
 exchange()
 Dual-range equal(), is_permutation(), mismatch()
 get<T>()
 tuple_element_t

Standard User-Defined literals

“s” for creating std::strings
 auto

“h”, “min”, “s”, “ms”, “us”, “ns”, for creating
std::chrono::duration time intervals
 auto

myString = "Hello World"s;
myDuration = 42min;
“i”, “il”, “if” for creating complex numbers
complex<double>, complex<long double>, and
complex<float> respectively
 auto
myComplexNumber = 1.3i;
C++17 Core Language Features

New or updated C++17 core language features
 Removing
trigraphs
 Resumable functions (proposal for C++17)
Removing Trigraphs

Trigraph = sequence of 3 characters
Trigraph
Punctuation Character
??=
#
??(
[
??/
\
??)
]
??'
^
??<
{
??!
|
??>
}
??-
~
Resumable Functions (proposal for C++17)


Based on concept of coroutines
Coroutine is a generalized routine supporting:
 Invoke
 Return
 Suspend
 Resume
Resumable Functions (proposal for C++17)

Visual C++ 2015 Preview resumable functions
restrictions
 64-bit
targets only
 Manually add /await compiler switch
 Manually disable /RTC1 (run-time error checks)
 Manually disable /sdl (additional security checks)
 Currently in <experimental\resumable>
Resumable Functions – Async Operations
future<int> calculate_the_answer() // This could be some long running computation or I/O
{
return async([] { this_thread::sleep_for(3s); return 42; });
}
future<void> coro() // A resumable function
{
2 cout << "coro() starting to wait for the answer..." << endl;
3 auto result = __await calculate_the_answer();
6/5 cout << "got answer " << result << endl;
}
coro() starting to wait for the answer...
int main()
main() is writing something
{
got answer 42
1 auto fut = coro();
4 cout << "main() is writing something" << endl;
5/6 fut.get(); // Before exiting, let's wait on our asynchronous coro() call to finish.
return 0;
}
Resumable Functions – Generator Pattern
#include <experimental\resumable>
#include <experimental\generator>
0
using namespace std;
using namespace std::experimental;
generator<int> fib()
{
int a = 0;
int b = 1;
for (;;) {
__yield_value a;
auto next = a + b;
a = b;
b = next;
}
}
1
1
2
3
int main()
{
for (auto v : fib()) {
if (v > 50) { break; }
cout << v << endl;
}
}
5
8
13
21
34
TS Library Features

New or updated Technical Specification library
features
 File
system “V3”
Productivity Improvements
Enhanced productivity & build-time
improvements
Productivity & Build-Time Improvements



Improved IntelliSense database buildup
Incremental linking with LTCG enabled
Incremental linking for static libraries


New fast PDB generation techniques: /Debug:FastLink




Changes to static libraries referenced by other code modules
now link incrementally
Substantially decreases link times
Object file size reduction
Multithreading in the linker
New Visual Studio Graphics Analyzer (VSGA)
Productivity Improvements

Simplified QuickInfo for template deduction
VC++2013
VC++2015
New Refactorings






Rename symbol
Implement pure virtuals
Create declaration or definition
Move function definition
Convert to raw string literal
Extract function (available from Visual Studio
Gallery)
New Refactorings
Improved Performance
Improved Performance

Improvements to automatic vectorization




Improvements to scalar optimizations




Vectorization of control flow (if-then-else)
Vectorization with /O1 (minimize size) enabled
Vectorizing more range-based for loops
Better code gen of bit-test operations
Control flow merging and optimizations (loop-if switching)
Better code gen for std::min and std:max
ARM32 code generation improvements
C++ Cross-Platform Mobile Dev
C++ Cross-Platform Mobile Dev

VC++ 2015 Preview has 2 compilers:
 VC++
compiler to target Windows platforms
 Clang to target Android (iOS coming in the near future)

Android support:
 Build
 Libs
 Build
C++ dynamic shared libs and static libs
are consumed with Java, Xamarin , …
Native-Activity apps, pure C++
Android Native-Activity App
Questions
?
Download