Kate Gregory Gregory Consulting Limited DTL403 Complete an evaluation on CommNet and enter to win!

Download Report

Transcript Kate Gregory Gregory Consulting Limited DTL403 Complete an evaluation on CommNet and enter to win!

Kate Gregory
Gregory Consulting Limited
DTL403
Complete an
evaluation on
CommNet and
enter to win!
Agenda
TR1 – shared pointer
C++ 0x
Auto
Lambdas
...
IDE improvements in Dev10
C++ and Standards
Additions to the standard come from many sources
Vendors (often with an implementation)
Language users
Some features are implemented by some vendors
years before they are in the standard
Some years after
The standard includes language keywords, rules,
and the STL
One way of telegraphing future standards additions
is with a Technical Report
VC++ Libraries – TR1
Short for “Technical Report on C++ Library Extensions”
Many classes and functions are Boost-derived
Developer productivity through libraries
tr1::shared_ptr
tr1::function, tr1::mem_fn, tr1::bind
tr1::regex
tr1::tuple, tr1::array, unordered containers (hash-based)
tr1::type_traits
Random number generators
No C99 support & no special math functions
TR1 Is Available Now
Originally released as a “Feature Pack”
Now rolled into Service Pack 1 for
Visual Studio 2008
Delivery vehicle also includes the MFC updates
Ribbon
Themes
http://www.microsoft.com/downloads/details.a
spx?familyid=FBEE1648-7106-44A7-96496D9F6D58056E&displaylang=en
What Is shared_ptr?
A templated...
non-intrusive...
deterministically reference-counted...
smart pointer...
(to a single object)...
that works with polymorphic types...
incomplete types...
and STL containers (sequence and associative)!
shared_ptr Is a Smart Pointer
Smart
Unlike auto_ptr, which was a stupid smart pointer
Sane copy constructor and copy assignment operator
Behaves like an ordinary value type
Pass and return by value and by reference as usual
Plays nice with const
Pointer
Overloads operator*() and operator->()
Conversion function to unspecified-bool-type
if (sp) //handy
sp * 5 //compiler error
No jagged metal edges!
shared_ptr Is a Template
Generalizing over types without forgetting types
shared_ptr<T>
“shared pointer to T”
shared_ptr<const T>
“shared pointer to const T”
const shared_ptr<const T>
“const shared pointer to const T”
“Look, Mom! No backwards reading!”
shared_ptr Is Non-Intrusive
You can instantiate shared_ptr<T> without modifying
the definition of T
reference count is not embedded
Works with built-in types: shared_ptr<int>
Use shared_ptr without changing your existing
types
Stop using shared_ptr for a type: don’t rip
plumbing out of it
Huge usability benefit for minimal perf cost
A type can be sometimes held by shared_ptr and
sometimes contained by another type
shared_ptr Is Deterministically
Reference-Counted
Deterministic
shared_ptrs collectively share ownership of an object
When the last shared_ptr dies, the object dies –
immediately!
Reference-Counted
shared_ptrs to object containing shared_ptrs to other
objects OK
Cycles of shared_ptrs not OK
Someone else has to ultimately own you
You can’t own yourself!
See weak_ptr
shared_ptr Owns a Single Object
A single object, not an array!
If you new up an array and hand it to a shared_ptr:
It will compile
It will trigger UNDEFINED BEHAVIOR
If you need...
a container: vector
a shared container: shared_ptr<vector<T> >
less overhead: shared_array
in Boost, but not TR1
or perhaps: shared_ptr<array<T, N> >
in TR1
Custom deleters are insufficient (no op[])
shared_ptr Works with Polymorphism
shared_ptr<Derived> is convertible to
shared_ptr<Base>
Works fine, doesn't screw up the reference count
Need to convert back?
static_pointer_cast<Derived>(spBase)
dynamic_pointer_cast<Derived>(spBase)
While we’re at it...
const_pointer_cast<T>(spConstT)
None of these throw exceptions!
There is no reinterpret_pointer_cast
Note: shared_ptr itself is not polymorphic
shared_ptr Works with Incomplete Types
struct X;
void fxn(const shared_ptr<X>& p);
X must be complete by the time that you
instantiate certain member functions of
shared_ptr<X>, such as its constructor from X *
If the constructor fails (e.g. to allocate memory
for a reference count), it must delete the X before
throwing, and deletion requires complete types
in general
shared_ptr Works with Containers
auto_ptr is not set up to be contained by
STL containers
The STL loves ordinary value types
auto_ptr does not behave like an ordinary
value type
shared_ptr is designed for STL containers
behaves like an ordinary value type
Wraps non-values like noncopyable and
polymorphic types in value’s clothing
Comes with operator<() for use in sets and maps
shared_ptr Is Good for:
Passing around copyable but “heavy” objects
efficiently (a simple version of move semantics)
Superseding auto_ptr
Holding dynamically allocated objects at local scope
Holding multiple dynamically allocated objects as members
Containers of shared_ptr
vector<shared_ptr<NoncopyableResource> >
vector<shared_ptr<PolymorphicBase> >
Any other STL/TR1 containers, especially caches:
map<Key, shared_ptr<NoncopyableResource> >
shared_ptr
Basic shared_ptr Use
shared_ptr<string> sp(new string("meow"));
Not:
shared_ptr<string> sp = new string("meow");
Guidelines
All occurrences of new[] and delete[] should already
have been replaced with vector
All occurrences of new should immediately be given to
a named shared_ptr
All occurrences of delete should vanish
Exceptions:
When implementing custom data structures like trees that
can’t be composed from the STL and TR1
When performance is absolutely critical
Manual resource management is extremely difficult to
do safely; consider it to be a last resort
shared_ptr Completes
The Resource Management Story
Destructors encapsulate resource release
Destructors are resource agnostic
Memory, files, sockets, locks, textures, etc.
Destructors are executed deterministically
STL containers enabled “one owning many”
shared_ptr enables “many owning one”
Object Category
Owned By Their
Destroyed When
Automatic
Block
Control Leaves Block
Data Members
Parent
Parent Dies
Elements
Container
Container Dies
Dynamically Allocated
shared_ptrs
All shared_ptrs Die
Adhering to C++0x Standard
What we’ve got now
TR1 standard library
What’s already coded for Dev10
Lambdas
rvalue references
auto
static_assert
What’s coming post Dev10
Concepts
Variadic Templates
decltype, nullptr, __func__
Thread Library
Container Initializers
Lambdas for C++
What’s a Lambda?
Lambda expression or lambda function: an expression that
specifies an anonymous function object
(From C++ Standard)
Imagine handing an operation or function (code) to some other
operation or function
For generic work
For concurrency
For readability
Eliminate tiny functions
Tiny Functions
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void print_square(int i)
{
cout << i*i << endl;
}
int main()
{
vector<int> v;
for_each(v.begin(), v.end(), print_square);
}
Why Does It Need a Name?
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector<int> v;
for_each(v.begin(), v.end(),
[](int i) { cout << i*i << endl; } );
}
Why Lambdas?
Enable functional style of programming
Complement for STL/TR1
Great building block for concurrency
Clearer code
New Language Features
Lambdas That Return Something
vector<int> v;
deque<int> d;
transform(v.begin(), v.end(),
front_inserter(d),
[](int n) { return n * n * n; });
transform(v.begin(), v.end(),
front_inserter(d),
[](int n) -> double {
if (n % 2 == 0) {
return n * n * n;
} else {
return n / 2.0;
}
});
Using Variables from Local Scope
v.erase(remove_if(v.begin(), v.end(),
[x, y](int n)
{ return x < n && n < y; }),
v.end());
v.erase(remove_if(v.begin(), v.end(),
[=](int n)
{ return x < n && n < y; }),
v.end());
for_each(v.begin(), v.end(),
[&x, &y](int& r) {
const int old = r;
r *= x * y;
x = y;
y = old;
});
static_assert
Custom Compile-time error messages
static_assert(SOMETHING_MAX == 7, “oh no”);
Most useful to template authors
template <int N> struct Something {
static_assert(N < 2, " Something<N> requires N < 2.");
};
// . . .
int main() {
Something<1> peppermint;
Something<3> jazz;
}
...error C2338: Something<N> requires N < 2.
test.cpp(8) : see reference to class template instantiation
'Something<N>' being compiled with [ N=3 ]
Rvalues and lvalues
Lvalue
E.g., x, *y
can be on the LHS side of an assignment
You can take the address
Rvalue
E.g., 2, foo(x), a+b
can only be on the RHS
You can’t take the address
You can pass by ref only if it’s a const ref
Where would the modified value be stored?
Rvalue References
Most useful to template authors
Allows huge performance improvements by moving
instead of copying and deleting
Non useful examples:
void f1(HugeThing h)
void f2(HugeThing& h)
void f3(HugeThing&& h)
Useful for functions that are part of a chain
Not about const-lying – really about ephemeral objects
string s2 = s1 + "a" + "b" + "cd";
Auto
Automatic type deduction
auto x = new HugeObject(42);
No more gnarly iterator declarations
for (auto it = v.begin(); it != v.end(); ++it)
Dev10 Architecture Changes
Intellisense decoupled from navigation
No need to reparse entire solution after
header change
No more .ncb file – SQL CE store instead
Much quicker to insert/update single symbol
Intellisense faster even in larger solutions
After a small code change
Switching build (e.g., debug to release)
Dev10 New Features
Quick Search
Find a symbol
Call Hierarchy
Calls From
Calls To
Replaces Call Browser
Red Squiggles
Without a build
New IDE Features
C++ Is Very Much Alive
Native code is still a fully supported way of life
Many Vista and Windows 7 goodies are native only
Interop is dramatically easier from C++
Templates offer power no other language can match
For both native-only and interop development
Microsoft is committed to C++
IDE improvements
MFC improvements
Language-level improvements
But don’t expect C++/CLI to be everything C# is
Wizards
Designers
And watch for more announcements from the C++ team
www.gregcons.com/kateblog
[email protected]
Resources
www.microsoft.com/teched
www.microsoft.com/learning
Sessions On-Demand & Community
Microsoft Certification & Training Resources
http://microsoft.com/technet
http://microsoft.com/msdn
Resources for IT Professionals
Resources for Developers
www.microsoft.com/learning
Microsoft Certification and Training Resources
Track Resources
Visit the DPR TLC for a chance to win a copy of
Visual Studio Team Suite. Daily drawing occurs
every day in the TLC at 4:15pm. Stop by for a
raffle ticket
http://www.microsoft.com/visualstudio
http://www.microsoft.com/visualstudio/enus/products/teamsystem/default.mspx
Please visit us in the TLC blue area
© 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should
not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS,
IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.