The last Channel 9 video interview seems to have been well-received, and some people suggested Charles should have asked about additional topics.
So here’s my idea: Let’s do another C9 interview, this time with your questions — hard or soft, big or small, just not too bizarre or personal please. :)
Here’s how I’ll try to take them:
- Post your question(s) below as a reply to this post. Post as many questions as you like, but please make each one a separate reply for better clarity.
- Return often to vote your and others’ questions up or down. That way I know what’s of interest to lots of people, rather than spending 10% of the interview answering something of interest to only one person.
- Charles will pepper me with the top-rated questions and we’ll get through as many as we can in some reasonable time (30 minutes? though once we get going we tend to be hard to stop). We’ll try to do it somewhere with a whiteboard as I expect that’ll be handy.
So, now it’s all yours… reply below as often as you like, and vote the questions up/down early and often.
Update, June 7: The followup interview is now live. Thanks for all your questions, and we took as many of the most popular ones as we could!
#pragma once does not work if you #include a copy of the header.
#import uses GUIDs assigned to modules, which is the same mechanism as #include guards, only more automatic.
You’re confusing Windows CE with desktop Windows. The existing hacks are there to handle the fact that Windows CE doesn’t have as wide an API as desktop Windows does, and in a few cases has behavioural differences.
Windows 8 on ARM will (I expect) be the traditional Windows desktop and server code ported to the ARM processor, and MFC is portable across processors. The existing source code will Just Work as there is very little code in there that is processor-specific. The little that is is limited to ATL window thunks and the implementations of IDispatch. If Microsoft don’t do it, you could probably do the tiny bit of porting work necessary and compile the library yourself (makefiles are supplied!).
I read and enjoyed the 2005 books:
C++ coding standards : 101 rules, guidelines, and best practices, Exceptional C++ style : 40 new engineering puzzles
Herb: will you be updating them or writing new books?
I wanted to know if there is any effort to enable the MFC in future versions of Visual Studio to be able to support the new Windows 8 ARM processor architecture. I am a bit concerned, because MFC are old but still very vital for many of the native developers, that it will not be extended to support the new ARM architecture of Windows 8. I remember having ARM based Embedded VC++ Version 3 in 2003 / 2004 which has already a major part of the MFC ported to ARM architecture.
I just wanted to help to point out that already a large part of the MFC is ARM compatible and it would maybe need only a few more parts to be converted to give the whole MFC full support for the ARM platform.
A concerned customer, Greetings!
What’s the status on the adoption of the C++11 memory model?
The language features in C++11 are nice but this is *the* big one.
Extending my GUI question early on…
Why isn’t microsoft thinking in terms of
1. A good customizable GUI (xaml/xml based RAD) tooling support for C++. With DirectX support.
2. A good C++ OOP libraries to support other technologies of the OS parts. ( some good app model around web, OPTIONAL )
3. C++0x full standard.
This will serve portable applications on all platforms phone/Tablet/PC. A developer can concentrate on one programming language (C++). Why we are being pushed to the limits with a non portable runtimes/plugins and misfitting frameworks ?
I am sure, if something like xaml/xml based GUI tooling is enabled for C++, then it will change everything for good.
Plausibility is overrated. ;-)
I started by manually following the first part of the Mr. Sutter’s second recommendation bullet (at the top):
“Return often to vote your and others’ questions up or down.”
… but then I remembered that I was a programmer … so I let my laptop take over clearing the browser cache, reloading the page, and doing the click-ity clicks.
I expect a few more people will join in on the fun … and express their excitement about C++0x in code.
Obviously, all … but maybe 5 … of the thumbs-up votes on the top three “Joshua Burkholder” posts are from me.
Energetically,
Joshua Burkholder
Actually, Cory writes about “polymorphic lambdas” and not about runtime polymorphism. So, please ignore first sentence from my reply above.
Also, not necessary polymorphic.
Why there is no type inference for this?
While not as beautiful as e.g. C#’s variant, it still would be useful to have:
[](auto x) { return x * 2; }
I don’t bring up language changes lightly either! as I said, boost::asio is a really nice library, but it’s still very verbose and difficult to learn. It’s about as good as you can pull off with a library. To improve any more, language integration is necessary.
C#’s new async features are like the holy grail of async – anyone who’s been doing it long enough in C++ will have wished for exactly what C# does.
counter argument: in C++ making changes to the language happens much more rarely than e.g. in c# – fortunately. things like this can be done in a library. dont integrate everything there is into the language itself, its complex enough.
wouldnt want the language to change its shape each year or two like in c#. c++ needs more stability.
Clang/LLVM comes to the rescue here.
We’ll be looking for the truly most popular questions that aren’t of interest to just a few people, so obvious hacking is counterproductive. But we’re also looking for questions that can be answered well in a video interview, and questions about code examples that are more than a line or two long make that harder.
Agreed. I’ve been tinkering with Boost.Enum, which is not part of the official Boost release but is in the Vault. It supports type-safety (mitigated by C++0x), string names, etc. See here: http://stackoverflow.com/questions/217549/which-typesafe-enum-in-c-are-you-using
Thumb up: 2361, Thumbs down: 3
If you’re going to hack the vote, at least make it seem plausible.
“‘C++ is expert friendly. But, it’s also novice hostile’, this is a direct quote from Bjarne Stroustrup. I can’t believe you’re doubting this.”
I am not and did not doubt this, but there are certainly better and worse ways of approaching C++ pedagogy. My point was that Koenig teaches C++ in a way that makes the language *less* hostile to novices, IMHO, but there’s always going to be a learning curve.
Is there a chance that we will get to_string() for enums. Would make it much easier to write and display certain stuff.
It’s merely an example of a function that takes a (ptr, size_t) pair. Most such functions don’t have an overload that takes a std::string& and std::string& isn’t the only ‘container’ that could be passed via such a pair.
@Olaf: IOStreams allows input/output of formatted and unformatted data (std::string, char*, int, double, user-defined structs/classes, etc.) … which is one reason why there are so many options to place your data in the stream; however,
operator<<
is the overloaded operator to use and program against for output andoperator>>
is the operator to use and program against for input. Here is an example of using these operators when dealing with standard out, standard in, file streams, and string streams://========================================
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main () {
string const filename = "fstream.txt";
string s1 = "s1";
string s2 = "s2";
string s3;
//----------------------------
// ostream
//----------------------------
cout << "ostream:" << endl;
cout << "s1: " << s1 << endl;
cout << "s2: " << s2 << endl;
cout << "s3: " << s3 << endl;
cout << endl;
//----------------------------
// istream
//----------------------------
cout << "istream:" << endl;
cout << "Enter s1 string: ";
cin >> s1;
cout << "Enter s2 string: ";
cin >> s2;
cout << endl;
//----------------------------
cout << "ostream:" << endl;
cout << "s1: " << s1 << endl;
cout << "s2: " << s2 << endl;
cout << "s3: " << s3 << endl;
cout << endl;
//----------------------------
// fstream
//----------------------------
cout << "fstream:" << endl;
fstream f( filename );
f << s1 << endl;
f << s2 << endl;
f.close();
f.open( filename );
f >> s2;
f >> s1;
f.close();
//----------------------------
cout << "s1: " << s1 << endl;
cout << "s2: " << s2 << endl;
cout << "s3: " << s3 << endl;
cout << endl;
//----------------------------
// stringstream
//----------------------------
cout << "stringstream:" << endl;
stringstream ss;
ss << s1 << s2;
ss >> s3;
cout << "s1: " << s1 << endl;
cout << "s2: " << s2 << endl;
cout << "s3: " << s3 << endl;
cout << endl;
return 0;
}
//========================================
This code produces the following output (assuming you typed “abc” for s1 and “wxyz” for s2):
ostream:
s1: s1
s2: s2
s3:
istream:
Enter s1 string: abc
Enter s2 string: wxyz
ostream:
s1: abc
s2: wxyz
s3:
fstream:
s1: wxyz
s2: abc
s3:
stringstream:
s1: wxyz
s2: abc
s3: wxyzabc
The book Standard C++ IOStreams and Locales by Langer and Kreft describes how C++ IOStreams are to be used … and (most importantly) how they can be extended.
Hope This Helps,
Joshua Burkholder
VC++ implements an old version of lambdas that makes a lot of sensible things not work. vNext is supposed to implement N2927 (New wording for C++0x Lambdas), so I suspect many of these issues will be solved.
i noticed that in the current version of vc++ using lambdas sometimes can disable ADL / König lookup to work as expected – for instance, i have to qualify for_each by prefixing it with std even though the iterator range is also of types within the std namespace (vector iterators for example).
how do ADL and lambdas interact in general (which would be my main question)?
do lambdas introduce something like temporary types that make ADL fail? what about ADL in lambda bodies?
looking forward to the next channel9 episode from c++ world !
Olaf, how would cout.write(s) differ from cout << s?
Examples are istream::read and ostream::write.
Instead of string s; cout.write(s.data(), s.size()); you could use cout.write(s);
I understand your distress. I had to learn C++ twice.
The first time, C++ was taught to me as C with minor changes: cout (instead of printf), class (instead of struct), new (instead of malloc), and delete/delete[] (instead of free). The pointers, arrays, and functions were all the same … OOP has emphasized, but templates and the STL were never mentioned … and I didn’t know they existed until years later. Everything was slanted towards a C-way of looking at things … even though the textbook I was studying from at the time kept stating that we needed to break free of the C mindset and concentrate on C++’s OOP way of thinking. It all seemed very cosmetic … all very C.
After using other languages at work for a number of years (and not using C++), I had to re-learn C++ again for a few projects. I decided to take a class again. The approach that the instructor used to teach C++ this second time around made all the difference. First, we started off learning the easy parts of the STL (like std::vector, std::back_inserter, std::for_each, …) and then we started on easy/useful function templates (like creating templates for operator<< to print out each element in a std::vector<T> … so we could just cout a vector). We went through iterators, vice pointers, and other containers, vice arrays. Then we went over classes and some OOP … and how they worked with generic programming. At the end, we covered the bit-twiddling, #define-ing, and pointer-obsessed nature that characterizes C.
This second approach worked for me. The first did not. My impression is that the presentation of C++ makes all the difference. There is no need to start with the C parts of C++ (like pointers, arrays, new, or delete/delete[]). There is also no need to present C++ as an OOP language that emphasizes C-like features (like pointers, arrays, new, and delete/delete[]). However, introducing C++ through the Standard Library using simple generic programming and simple OOP seems to work well … and C++1998/2003 fits that bill.
With C++0x’s auto and alternative tokens (like “and” for &&, “or” for ||, …), the next version of C++ will be easier to read for novices … and potentially easier to program. With C++0x’s std::make_shared, we can get rid of most (if not all) of the calls to new and delete … and deal solely with std::shared_ptr. With C++0x’s range-based for loop, iterating over collections will be easier for everyone (including novices). With lambdas and decltype in C++0x, STL functions like std::for_each and std::transform will be dramatically easier to use. With C++0x’s uniform initialization, it will be easier for everyone (including novices) to work through ideas in C++ code because we’ll be able to initialize vectors, constructors, etc. in the same way we have been able to initialize arrays of ints (making C++ more scriptable without compromising performance).
C++0x may be vastly easier for novices to learn … but their C++0x instructor can always make it difficult … and the book they use for C++0x can always be written from a perspective that was relevant 30 years ago.
Joshua Burkholder
What “ptr pair” and const std::string& functions from the C++ Standard Library are you referring to?
Please, provide a small code sample that demonstrates how you are using these functions.
Very Respectfully,
Joshua Burkholder
#pragma once // supported by GCC and VS, not sure what compilers do not support it
Data/String Ref (ptr pair) class/wrapper
A lot of functions have a (ptr, size_t) pair or a const std::string& parameter. The latter requires you to construct a std::string which isn’t necessary while the former requires the use of two parameters which isn’t handy.
Why does C++ not have a class/wrapper for this?
Class Properties
C# and Ruby have them (AFAIK) and they’re very handy. What’s your opinion and is there a chance to see them in C++ in the future?
Ignore the previous question, it finally hit me what is going on.
I just watched the presentation, and was trying to convert some of my existing code to use lambdas and algorithms.
I tried the following in VS2010 Pro (snippet from actual code. It exists in a static member function of a class that exists in the namespace KS::Math)
typedef vector storage_type;
typedef typename storage_type::value_type value_type;
std::string Input(“12345”);
storage_type Translate(5);
std::for_each(Input.rbegin(), Input.rend(), [&Translate](std::string::value_type Value)
{
std::fill(Translate.begin(), Translate.end(), 0);
// The next line produces the error – Error 1 error C2440: ‘=’ : cannot convert from ‘KS::Math::`anonymous-namespace’::’ to ‘unsigned int’ e:\programming\ksframework\branches\sandbox\src\kslibrary\math\bigintegermath.hpp 2619
Translate.front() = [&Value]() -> value_type
{
switch(Value)
{
case ‘0’: return 0;
case ‘1’: return 1;
case ‘2’: return 2;
case ‘3’: return 3;
case ‘4’: return 4;
case ‘5’: return 5;
case ‘6’: return 6;
case ‘7’: return 7;
case ‘8’: return 8;
case ‘9’: return 9;
default: throw std::exception();
}
};
}
As mentioned in the comment above, VS spits out a C2440 error saying it can’t convert from ‘KS::Math::`anonymous-namespace’::’ to ‘unsigned int’
I changed the code to
auto CharToInt = [&Value]() -> value_type
{
switch(Value)
{
case ‘0’: return 0;
case ‘1’: return 1;
case ‘2’: return 2;
case ‘3’: return 3;
case ‘4’: return 4;
case ‘5’: return 5;
case ‘6’: return 6;
case ‘7’: return 7;
case ‘8’: return 8;
case ‘9’: return 9;
default: throw std::exception();
}
};
Translate.front() = CharToInt();
This version compiles just fine.
Is there something I’m doing wrong with the first version, or can it just not work without storing the lambdas in the variable first?
Do you have an opinion on Intel TBB? Do you some similar library being integrated into the standard?
25-50% is an overstatement. the C++ committee can’t even vote out triagraphs !!!
C++ has been hijacked by experts and it’s so novice hostile. that is a fact. the better way is to accept the fact and think of solutions.
@Cory Nelson : I know WPF well and there are times when you really wish you want a C++ GUI. With WPF you are at the mercy of the framework. (i.e. you cannot go beyond the framework or .net framework ) There are many I can point out… When you write custom applications, that are really different from regular apps, you end up writing lot of interop stuff and it just feels like you just made a salad. As a C++ dev, I just want to be in C++ and not studying and reading about the WPF and C#.
I’m not sure how much you’re allowed to tell us, but I would *love* to hear some details about MS Windows and/or MS Office; how much C vs. C++, which parts of C++ do they use etc (Google has released an “official” C++ coding standard, but I would love to see something similar from the MS Windows and MS Office teams…)
WPF fulfills all those requirements.
I guess you meant one in C++, but… why do you need to write a GUI in C++? Backend, sure, but GUI?
Will Visual C++ allow lambda functions with no captures to be converted to their associated function pointers (per the C++0x Draft Standard)? Or does Visual C++ interpret the C++0x Draft Standard differently on these type of lambda conversions?
Background:
In Section § 5.1.2 Paragraph 6 (on Page 94) of the 2011-04-05 C++0x Draft Standard (N3291=11-0061), a lambda function with no captures should be able to be converted to a function pointer having the same parameter and return types as the lambda. Currently, g++ 4.5.2 seems to implement this; however, Visual C++ 2010 SP1 does not seem to implement this. For instance, the following code compiles on g++ 4.5.2, but __not__ on Visual C++ 2010 SP1 … Visual C++ issues a compile-time error at the “f = lambda_1” line:
#include <iostream>
using namespace std;
void function_1 ( void ) {
cout << "function_1" << endl;
}
void function_2 ( void ) {
cout << "function_2" << endl;
}
auto lambda_1 = [] ( void ) -> void {
cout << "lambda_1" << endl;
};
int main () {
auto lambda_2 = [] ( void ) -> void {
cout << "lambda_2" << endl;
};
//-------------------------
typedef void (*F) ( void );
F f;
f = function_1;
f();
f = function_2;
f();
f = lambda_1;
f();
f = lambda_2;
f();
f = [] ( void ) -> void {
cout << "lambda_3" << endl;
};
f();
//-------------------------
return 0;
}
When this code is compiled using g++ 4.5.2 and run using the following command lines:
g++ -o main.exe -std=c++0x -march=native -O3 -Wall -Wextra -Werror main.cpp
./main.exe
The following output is generated (as expected):
function_1
function_2
lambda_1
lambda_2
lambda_3
When will this compile/work in Visual C++?
Very Respectfully,
Joshua Burkholder
I see a lot of great questions here! I’m looking forward to answering as many as we can.
I’ve updated the blog post to note that the followup interview has been scheduled for next week, so you have until midnight June 1 (North American Pacific time) to post new questions and vote others’ questions up/down. I’ll blog a reminder a day or two before the cutoff.
So… what’s the alternative? A language that effectively breaks 25-50% of all existing code every time a new version comes out?
If you tried to do that, then what you have is not a single evolving language. What you will have is multiple, *incompatibile* languages. Every new “version” will be a new language that will have new compilers. Users will pick a specific version and code to it rather than “upgrading” to something “cleaner”. Compiler developers will have to essentially support multiple compilers for the supposedly same language.
Really, if you’re going to break most code with a new “version” of a language, just write a new language. It would be better than carrying on the pretense that we’re talking about a “version” change.
Hi Herb,
Thanks for your efforts and time spend on this Q&A.
Is it time for Microsoft to introduce a GUI framework for the 21st century ? what we have now is, things before the internet era. We are still dragging it along with us, aren’t we ? When will be see an good GUI framework based on DirectX and supporting API libraries ?
thanks
“C++ is expert friendly. But, it’s also novice hostile”, this is a direct quote from Bjarne Stroustrup. I can’t believe you’re doubting this.
I think C++ has been taken hostage by it’s success. You can’t remove a bad feature because there is some code “out there” that depends on it — i believe this is too much emphasis on backward compatibility.
I think C++ needs to wash itself and remove the dirt.
There is no unicode encoding conversion operation, if that’s what you’re asking for.
For #4 above, a raw string requires an
R
in front of theraw-string
. An example of using a raw string is the following … assumed to be in main.cpp:#include <iostream>
using namespace std;
int main () {
cout << R"("C:\Program Files\")" << endl;
return 0;
}
This code doesn’t currently compile in Visual C++ 2010 (because C++0x raw strings aren’t yet implemented); however, g++ 4.5.2 has no issues … so if we execute the following on the command lines:
g++ -o main.exe -std=c++0x -march=native -O3 -Wall -Wextra main.cpp
./main.exe
Then main.exe will compile and run … producing the following output:
"C:\Program Files\"
Very Respectfully,
Joshua Burkholder
What C++0x features are being added to Visual C++ 2011?
Specifically, are the following being added to Visual C++ 2011?:
1) std::initializer_list
2) std::thread
3) range-based for statement (i.e.
for ( for-range-declaration : expression ) statement
)4) raw strings (i.e.
raw-string:"optional-d-char-sequence(optional-r-char-sequence)optional-d-char-sequence"
)Very Respectfully,
Joshua Burkholder
Please, disregard this post. The angle brackets and tab spacing did not come through (esp. in the code).
Below is an identical post that has the angle brackets and better spacing.
Very Respectfully,
Joshua Burkholder
Mr. Sutter,
My previous post did not take into account angle brackets and tab spacing; therefore, please delete/disregard my previous post.
Here is my question:
In C++0x, will decltype(std::vector<std::string>())::value_type become valid? And will it be the same as std::string?
If not, why? And what chapter/section of the C++0x draft standard prevents this decltype(…)::some_type (i.e. the ::some_type as a nested type of the decltype(…) call)?
Background:
If we have the following code:
<code>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
int main () {
vector<string> strings;
strings.push_back( “Hello” );
strings.push_back( “World” );
for_each( strings.cbegin(), strings.cend(), []( decltype(strings.cbegin().operator*())& str ) {
cout << str << endl;
}
);
return 0;
}
</code>
Then, str is a const std::string & and the output is as follows:
Hello
World
However, in Visual C++ 2010 SP1 and g++ 4.5.2, the (arguably) more-readable code cannot compile:
<code>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <type_traits>
using namespace std;
int main () {
vector<string> strings;
strings.push_back( “Hello” );
strings.push_back( “World” );
cout << “Is decltype(strings) the same type as vector<string>? “;
cout << ( is_same<decltype(strings), vector<string>>::value ? “Yes.” : “No.” ) << endl;
for_each( strings.cbegin(), strings.cend(), []( decltype(strings)::value_type const & str ) {
cout << str << endl;
}
);
return 0;
}
</code>
Both Visual C++ 2010 SP1 and g++ 4.5.2 do not accept decltype(strings)::value_type as a type, even though vector<string>::value_type is an acceptable type.
One workaround to this is to create a typedef of just decltype(strings) prior to writing out the lambda, but that isn’t quite as satisfying as just using the decltype() immediately where it is needed. In other words, this code does work:
<code>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <type_traits>
using namespace std;
int main () {
vector<string> strings;
strings.push_back( “Hello” );
strings.push_back( “World” );
cout << “Is decltype(strings) the same type as vector<string>? “;
cout << ( is_same<decltype(strings), vector<string>>::value ? “Yes.” : “No.” ) << endl;
typedef decltype(strings) STRINGS_TYPE;
for_each( strings.cbegin(), strings.cend(), []( STRINGS_TYPE::value_type const & str ) {
cout << str << endl;
}
);
return 0;
}
</code>
Very Respectfully,
Joshua Burkholder
In C++0x, will decltype(std::vector())::value_type become valid? And will it be the same as std::string?
If not, why? And what chapter/section of the C++0x draft standard prevents this decltype(…)::some_type (i.e. the ::some_type as a nested type of the decltype(…) call)?
Background:
If we have the following code:
#include
#include
#include
#include
using namespace std;
int main () {
vector strings;
strings.push_back( "Hello" );
strings.push_back( "World" );
for_each( strings.cbegin(), strings.cend(), []( decltype(strings.cbegin().operator*())& str ) {
cout << str << endl;
}
);
return 0;
}
Then, str is a const std::string & and the output is as follows:
Hello
World
However, in Visual C++ 2010 SP1 and g++ 4.5.2, the (arguably) more-readable code cannot compile:
#include
#include
#include
#include
#include
using namespace std;
int main () {
vector strings;
strings.push_back( "Hello" );
strings.push_back( "World" );
cout << "Is decltype(strings) the same type as vector? ";
cout << ( is_same<decltype(strings), vector>::value ? "Yes." : "No." ) << endl;
for_each( strings.cbegin(), strings.cend(), []( decltype(strings)::value_type const & str ) {
cout << str << endl;
}
);
return 0;
}
Both Visual C++ 2010 SP1 and g++ 4.5.2 do not accept decltype(strings)::value_type as a type, even though vector::value_type is an acceptable type.
One workaround to this is to create a typedef of just decltype(strings) prior to writing out the lambda, but that isn’t quite as satisfying as just using the decltype() immediately where it is needed. In other words, this code does work:
#include
#include
#include
#include
#include
using namespace std;
int main () {
vector strings;
strings.push_back( "Hello" );
strings.push_back( "World" );
cout << "Is decltype(strings) the same type as vector? ";
cout << ( is_same<decltype(strings), vector>::value ? "Yes." : "No." ) << endl;
typedef decltype(strings) STRINGS_TYPE;
for_each( strings.cbegin(), strings.cend(), []( STRINGS_TYPE::value_type const & str ) {
cout << str << endl;
}
);
return 0;
}
Very Respectfully,
Joshua Burkholder
do you thing that there should be foreach like “for_each_in_range” . something like for(auto element55:my_multimap.equal_range(55));
Can you comment on how type deduction (auto, decltype) relate to “private types” such as std::vector<bool>::reference or types created when writing expression templates?
I’ve written a post that suggests that `auto` reduces safety of C++ in these scenarios and I would like to know if I’m missing anything and if this problem (or lack thereof) was discussed.
Here’s a link to the post I mentioned:
http://lanzkron.wordpress.com/2011/02/21/inferring-too-much/
Tnx for the first part, but there is no u16cout:
http://stackoverflow.com/questions/6020314/why-is-stdu16cout-missing
One of the things that make c++ look old are the include guards. Is there any chance that it will be “fixed”? Can it be fixed?
Wiki says that objC “fixed”:
The Objective-C language (which is a superset of C) introduced an #import directive, which works exactly like #include, except that it only includes each file once, thus obviating the need for #include guards.[1]
It’s a lot easier to write incomprehensible C++ than it is to write incomprehensible C. Unfortunately this is the stuff most coders end up seeing first, and many end up with such a skewed view that they never actually try C++ long enough (if at all) to see its strengths.
It doesn’t help that you need to be coding C++ for 5+ years to really understand its strengths and see all the cool stuff it can do!
In your opinion, which isthe programming language that is the main “concurrent” of C++ ? I mean: a “second-choice” language, capable of offering features similar to C++, and which can be thought as an alternative for coding.
Is it plain C ? Java ? C# ?
Sadly, this hostility exists. Have you ever read what the developer of one of the most famous operating systems (i.e., Linus Torvalds) has written about C++ ? You can read at
http://thread.gmane.org/gmane.comp.version-control.git/57643/focus=57918
A nice answer to him can be found here:
http://warp.povusers.org/OpenLetters/ResponseToTorvalds.html
Seing changes as “create/update/delete”, adding new features is “easy”, as happened for most part in C++11, also “deleting” features is possible: deprecate them, or, as a user, just don’t use them.
What’s hard is “changing” and it’s even harder the more fundamental the language element. Still there should be some means to do so.
If there is no means, then it may be as with certain software: rewrite from scratch (with lessons learned) every X years.
Other newly created language take advantage of experience C++ had with language elements in the past. C++ should have this advantage, too.
When it comes to “not breaking old code”, I’m sure there are strategies available similar to what large software libraries do when introducing breaking changes, iow it’s solvable.
That is all well and good. Do you know though if there is anything in C++0x that makes converting between the different string types with less boilerplate? Something like std::lexical_cast?
Uniform initialization (the use of {} to call constructors when the type being constructed can be deduced) has the potential to radically reduce the quantity of typing necessary to create C++ types. It’s the kind of thing, like lambdas, that will change how people write C++ code. What is the Visual Studio team’s priority for implementing this feature, along with initializer lists?
Neither of those is true. std::basic_string is a template type, which is templated on the character type. All std::string is is a typedef for a particular template instantiation of std::basic_string. The iostream classes are the same way. C++11 will include typedefs for std::u16string and std::u32string, which use char16_t and char32_t respectively. I honestly don’t recall if there will be a std::u16cout or std::u32cout, but I wouldn’t be surprised if there was.
I guess I should clarify this question as a two-parter: one, about verbosity:
[](int x) { return x * 2; }
VS C#’s
x => x * 2
Where the difference can grow very large depending on how many parameters and how large the type names are. While better than defining your own complete functor type, it can still be inconvenient.
It seems to me like such a short form could work for C++, and map into a polymorphic lambda.
Which leads to the second part: why did polymorphic lambdas fail and what work is being done to bring something like them back? I understand there was some difficulty making them work with concepts–could you go into more detail?
2. do you think that it is awful idea to have <= in the standard when it comes to size of data types. I mean for example: long long, long, int…
Two specific question.
1AFAIK there is no way to have a (w)string that uses char16_t chars for storing individual characters. Also AFAIK there is no nice way to pring char16_t chars with (w)cout. Do you think that is a small but ugly problem with c++11?
Actually what C++ really needs is a decent replacement for printf (varadic templates anyone?) rather than the other way around.
Not sure how you would define a naked unowned pointer either
“I think C++ is a lot less novice-hostile than C, if taught properly. Learning about vectors is easier than learning how to manage arrays, for example.”
See Andrew Koenig’s on-going series on teaching C++ over at DDJ. There and in his _Accelerated C++_, he does just this, but there is a good bit of back-lash from the old C hands who retort that arrays should be taught first.
“I think a ‘cleaner’ C++ has to be designed from scratch that breaks free from these.”
See D, Go, Java, C#, etc. etc. etc. ad nauseam, but that destroys C++’s main advantage: it’s massive code base and user community.
C++ may now be a bit pock-marked and scarred, but those are battle scars from actual use in almost every conceivable environment — something the language redesigns just don’t have and may never have.
Momentum is a hard thing to build.
“I’d be happy if C++ would fix design flaws, even if it breaks my old code.”
I think you are in the minority. Python is a pain every time it breaks my code, and there is a LOT more mission critical C++ code out there to be broken surreptitiously.
Although Herb is a regular critic of std::string’s overzealous, fat interface, changing the semantic meaning of std::string::replace() at this juncture would be diabolical. They could add a new function, but I doubt that will happen.
On the other hand, I think std::auto_ptr will be deprecated in favor of std::unique_ptr in the new standard (right?).
But template parameter type inference could have done the job:
[](auto x) {} could be equivalent to
struct mylambda {
mylambda(){}
template
void operator(T x){}
};
Not compile the C-standard library? Even though the C++ standard library *includes* it? It seems rather silly to throw out cool things like “printf”, especially when they take up less compile-time space than more complex iostream-based IO.
And how would you define a “naked unowned pointer” anyway? Any object that holds that pointer would necessarily have to store a “naked unowned pointer” within itself.
One of the biggest advantages of C++ is that I can pick and choose between C++ *and* C libraries. I don’t have to use one or the other; I get both. I can use LibXML2 right alongside Boost; I don’t have to use unpleasantness like Xerces simply because Xerces is C++ and LibXML2 is C.
It should be noted that the “OpenGL deprecation mechanic” does not allow Khronos to redefine existing OpenGL functions. It simply says “don’t use this anymore”. So you could never do that thing like making “wchar_t” into “char” (not that you would want to even if you could. Not everyone wants to use UTF-16; some of us like UTF-8).
Multi-threaded applications need multi-threaded scalable memory allocator, will we have somewhat like Intel TBB scalable memory allocator, or Google tcmalloc in “VC Next” ?
Could you tell something about how to promote the new standard in all C++ programmers (not just C++ fans), on perspective of a committee member or of a compiler producer?
Can you give some history and reasons for the current definition of the noexcept feature?
There have been a lot of questions asked about the history and usefulness of noexcept on comp.lang.c++. Generally views of people on the list were fairly negative of the current definition and there is obviously a lot of confusion.
I understand why we want something to define that a function does not throw, but are we making the same mistakes with noexcept() as we made with throw()?
http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/fe0aff369259d1c7/4bd39b265a0f1eb8
http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/791fdb99ca834dc6
That article seems to be advocating just running synchronous code in another thread, as a replacement for truly asynchronous code?
I think this would work for a lot of trivial use cases, but it definitely won’t scale. C#’s async support is a much better solution.
I’m not at all worried about not understanding the Boost code. I can use it, and that’s what really matters. If I wanted to understand Boost, I’d work on it until I could.
Libraries of various sorts are ways of writing code so you don’t have to. Binary search is particularly hard to get right, so you use a library. Most people couldn’t write a good log function, unless they could pass it off to hard-coded silicon. If you look at implementations of C++ standard libraries, you’ll find a lot of hard-to-understand stuff.
I think C++ is a lot less novice-hostile than C, if taught properly. Learning about vectors is easier than learning how to manage arrays, for example.
Programmers are encouraged to introduce concurrency in their code in order to harness the full power of today’s computers. Languages such as C++ are being extended to support parallelism either natively or through libraries.
Given the difficulty for programmers to reason about the program’s behavior when concurrent and asynchronous code is involved, aren’t you concerned that the next generation of programs could harbor subtle bugs that would make them unreliable – and even dangerous to use if the system is responsible for performing life-critical tasks?
When will your next books be released? In special, Effective Concurrency and Speaking of C++?
Unlike the most of your readers, I’m not a C++ exprert, I’m just studying C++ (and so I’m catching its “novice hostility” in the neck :-)) , so what represents a real value for me and for people like me are the books like your “Exceptional C++” and “More Exceptional C++” that clarify HOW to write a stable C++ code.
The C++11 Standard has more than 1000 pages and this is slightly frightening :)
So, the question that seems important due to all aforementioned, when can we expect C++ books covering this brave new standard and showing the best ways of using new features? And personally you – are you going to make us happy with your new book before long? ;-)
There has been some “fuss” about automatic parallelization in perhaps more academic circles, so as to provide parallelism as a service on equal footing with garbage collection. What do you think about automatic parallelization or perhaps automatic asynchrony?
I just read this (albeit a bit dated) article
Prefer Futures to Baked-In “Async APIs”
http://drdobbs.com/high-performance-computing/222301165?pgno=1
This article seems to advocate a style where asynchrony is a call-site issue, meaning the callee does not provide special support for asynchrony but rather the caller can just make a future and await that if necessary.
What do you think about C# Async (CTP) in this respect, as methods are now decorated with Task (of T?).
This makes it explicit in the method signature when a method can be “run” asynchronously, but it also requires decorating methods with a particular type (or you can implement awaitability for other types).
C++ nowadays have many detractors that see it as a language that is becoming too complex, hard to understand and slow to evolve. There are entire books and websites devoted to its quirks, writing compilers and tools becomes harder and harder as it is finding experts.
Still C++ is surely the king in its class, mostly due to its widespread support.
Do you think C++ can keep growing, or do you envision an end, and a successor to it? What’s your opinion on the health of the language, is it a dying language in dire need of a successor, or do you think it’s only in its youth?
Many-core processors are starting to become a reality, and our current methods of writing performant, safe, concurrent code are inadequate.
Writing good multithreaded code is very hard, writing good lock-free code is even harder, and I believe Software Transactional Memory is a false prophet.
It suffers from the same issues as locks, finding the right granularity to wrap operations in is difficult; too big and performance suffers, too small and you have race conditions (or live locks in the case of STM).
Given that, what do you think concurrent code will look like in the future, and do you think there are any upcoming programming paradigms that will take us beyond where we are now?
I think Boost is a particularly bad example of C++ that shouldn’t weigh in on the “expert friendly” discussion.
Most people will only worry about compatibility with a small set of well-known, fairly compliant compilers — GCC 4.x, VC++ 9/10, etc.
In contrast, Boost takes great strides to be compatible with all sorts of compilers with varying compliance, so it has a lot of ugly code.
EASTL does have a number of interesting bits which I hope get into a future C++ standard.
One thing about C++ that’s always irritated me is the inflexibility of allocators — for instance, they aren’t well suited for allocating an entire object hierarchy from a single arena, which can be very important for efficiency in some situations.
Thank you.
As soon as I read the “syntactic sugar for functors” part, I did a big “Doh!” I knew that yet forgot about it when I wrote the question.
Thanks again.
I’ll answer the first one for you. Remember that lambdas are just syntactic sugar for functors. You cant use the auto keyword in place of the type of an argument in a function declaration. Auto works by deduce the type from declarations, so you cant use auto in the declarations themselves.
This is a good question I find there is lots of hostility towards C++ in the open source and embedded communities. Why is this? Could you talk about why C++ is as good a fit as C, for micro-controllers? The embedded programmers fear silent usage of dynamic memory but with templates and std::array etc there are valid alternatives. Unfortunately the rare C++98 compliant compilers that exist for micro-controllers costs thousands of dollars. I wish MS got in this game. Is there any hope of this?
While personally, I wish the standard would have used ‘let’ instead of ‘auto’ for type interference, I understand not wanting to add another keyword to the spec.
However their does seem to have strange limitations.
1- can’t use the auto keyword for a lambda parameter list. The parameters are easily deduced from the either the collection being used or how they are used in the lambda itself.
2- they can’t be used to capture function pointers as so:
auto addGroupieFn = vectorOfC_PlusPlusRockStarsGroupies.push_back
C++ is too expert friendly. But, it’s also novice hostile. I have written useful C++ code and yet I couldn’t understand most of the boost code.
I think C++ has been taken hostage by:
1. its own success (perhaps trillions of LOC exist)
2. a bunch of experts who control the committee and put too much emphasis on backward compatibility.
I think a “cleaner” C++ has to be designed from scratch that breaks free from these.
What is your opinion??
C++ has been around for around 2 decades. However, it has been seldomly used for the development of kernels of operating systems. How many C++-based operating systems are you aware of ?
Smart pointers are one of the most appreciated parts of the Boost library. In fact they have been proposed to be included in C++0x as well.
Some developers, however, fear that their usage can lead to a poorly designed code, since the developers don’t have to care about the actual scope of allocated object.
So: what’s your personal feeling about smart pointers ? Are they really a needed feature of C++, or they just lead to a worse code in which nobody can understand where objects are destroyed ?
Love the filtering! Let me try various other ways:
multiset < int, decltype(less) > c(less);
multiset /*greater than*/ int, decltype(less) /*less than*/ c(less);
Talk about readability! :-)
:-( let me retype this as:
int local;
…
auto less = [&local] (int l, int r) {
return l + r < local;
};
multiset c(less);
…
Can you compare the code below to the one using a Functor? (e.g. inlining, readbility, …)
int local;
…
auto less = [&local] (int l, int r) {
return l + r < local;
};
multiset c(less);
…
Thanks.
Can you please comment on the influence of the boost community on the development of the new features of the c++ language. It seems that a lot of new C++0x features/additions have been adopted due to the wide use/acceptance of the feature/s as part of the boost library.
Could you discuss briefly the module support that didn’t make it into C++0x please? How can this work with templated code that has a lot of functionality in headers?
Long shot.. but I’ll add:
New Iterator Categories? (Separating Traversal traits from Access traits)
Adding Range-Based algorithm overloads?
My biggest annoyance with C++ at the moment is its reliance on the C Preprocessor.
I heard that there was a proposal to add modules to C++0x which was bumped to a future version.
The D programming language seems to have several clever solutions to remove the need for text macros (such as string mixins).
I hope that you would prefer a world without need for the CPP but the task does seem insurmountable.
So, question: Could your share your thoughts on an optimistic scenario/timeline in which C++ removes its reliance on the CPP.
(p.s. C++ will always rely on CPP for backward compatibility, I mean to remove reliance in future applications)
Are there any plans for adding Multimethods to C++ in the future?
I read a paper once that Bjarne had written outlining a plan, but I don’t know if it was presented for C++0x — do you recall?
STL: Any chance to see a large-scale STL update with new allocators and improved containers/algorithms, similar to the EASTL proposal?
Modules: Are they really coming, and if so, when do you expect the first implementation?
For years MS has been pushing .NET/WPF as the way of the future of programming Windows. Much to the dismay of those with large C++ code bases. As such, when we are hiring, very few candidates have C++ experience or the will to learn it as they view it as obsolete. Those that do have experience don’t want to “go back to that” and want to move forward. Thanks to MS itself for that.
Thus, we are in a position where we may have to migrate this large code base to .NET/WPF where it really doesn’t buy us much other than future developers to maintain and work on our code base.
So, why the long time in C++ standardization work? Will the next standard take as long? Will MS or the C++ committee be working on getting newer developers to take a look and learn C++ along with managed languages? It seems the damage has been done. Other languages/platforms are moving a lot faster than C++. I realize legacy factors in, but still…
By the way, I like what is gong on in C++11 and am encouraged from a language standpoint. It’s the real world business side that has us troubled.
Cory asked: * Threading — thread pools, fine-grained task model, thead-safe containers.
Cory asked: * I/O and Async — something like boost::asio is needed, but that’s still a bit unwieldy on the async part — language integration like C#’s async would be even better. any thoughts on this?
Cory asked: * Filesystem — something like boost::filesystem is desperately needed.
Cory asked: * Verbose lambdas — The lambdas we have right now are very nice, but verbose compared to C#’s. Polymorphic lambdas could have helped solved this — again, why did they fail and what work is being done to bring something like them back?
Let me break these up so they can be voted on individually:
Cory asked: * Concepts — why did they fail and what work is being done to bring something like them back?
How does the new standard influence language C++/CLI extension?
In OOP people have learned to use the clone pattern to do polymorphic copy construction. The C++ language does not help with the boiler plate though, but its easy enough to write yourself. When it comes to polymorphic copy assignment though.. well the boiler plate for this is impractically hard to write yourself. The fact that the language does not help you do polymorphic copy construction, and copy assignment seems like a fundamental gap in the type system of the language. Would you agree? I think this is one of the reasons why OOP programming is such a pain. Maybe multimethods could help fill this gap?
> I think an official “C+” which removed some parts of C++ could be very interesting.
Actually there is such a langauge and it is called EC++. Its got all the bad part of C and few of the good parts of C++.
I actually agree with the need to isolate a safe subset though, but think that rather than remove one of the big plusses of the language (say templates) and get a C+ subset.. we need to remove some of the C subset from the language and get a ++ subset. It would be nice to have a compiler switch that wouldn’t compile c-style casts, implicit conversions to void*, that lacked a C standard library, etc. Maybe one could even get warnings about using c-arrays, and naked unowned pointers.. etc.
Why C++0x does not handle such issue as “local template class”?
As an application programmer, when do I need to worry about implementing rvalue references for my classes? I get the gist of them, but can I safely ignore them most of the time? When can I not?
Are these too personal: How did you wind up on the C++ committee? Where have you worked? Where did you go to school?
What sport do you practice?
What always has been (and still is) the biggest plus in C++ is having control over memory, performance and hadware. But today developertools are also an important topic (e.g. for refactoring). Since it is really hard to parse C++ a lot of tools are still missing or not as powerful as the ones for Java and C#. Now there are languages like Go or D which offer the same (or even more) amount of control as C++ and are much better prepared for supporting tools then C++. So do you think that lacking toolsupport for C++ will be a major problem since there are new better-prepared system-programming languages available?
Thats an interesting question, if the C++ Committee have any plans to implement some sort of mechanics like the Khronos/OpenGL deprecation mechanic, or like Java an atribute ‘deprecated’. Or like static_assert but for emit warnings instead of errors.
What is the strategy to deal with C++ language and standard library design flaws in the long run?
Being almost 100% backwards compatible seems a major design goal. But there is the risk of having old, obsolete features blocking new design improvements.
An example of what I mean is std::string::replace. Every time I do a replace I want the notion of “replace this substring by another substring”. But instead there are about 10 overloads which don’t help. Another one is “char” which should be probably called “byte” and “wchar_t” be “char”.
I know one can get used to everything and there are always workarounds. But all of these problems are accidential and not inherent.
Natural languages evolve over time by simply “not using” certain phrases. C++ doesn’t seem to have this ability. My stance on this is, I’d be happy if C++ would fix design flaws, even if it breaks my old code.
What do you think about this, are you afraid “bad design decisions” may accumulate over time, thereby making it more and more harder for newbies to learn the language?
+1
What are the reasons for not including C99 features like local variable length arrays, restrict and hex floats in C++11?
I’m not sure how interesting this would be for a C9 question, but polymorphic lambdas? Why didn’t we get them?
IIRC, they were made problematic by concepts, but now that concepts are gone, wouldn’t it have made sense (time permitting) to make lambdas polymorphic? Do you think that might happen in a future revision?
How do you personally feel about concepts? Both the specific proposal that was eventually thrown out, and then general, well, concept?
What do you think of the “Embedded C++” idea ?
C++ is a *very* powerful and complex language, and I feel that the gap between C and C++ is too big…
A lot of people (including me) only use a subset of C++ (as it is too complex for many to understand), but the problem is then “which subset” ?
I think an official “C+” which removed some parts of C++ could be very interesting both for learning purposes (you could learn C+ first, and then later on move to C++ if you desired) and for efficiency/simplicity (using C++ for the system-level development, and C+ for the application-level development).
I know it will never happen, but I think it could actually *strenghten* C++’s position as it would enable more developers to “graduate” from C towards C++.
(if we had a new, simplified standard (cross-platform) library inspired by Python’s libraries/.Net etc and a C+ interpreter as well,, we’d be set ;-) )
Cory, please split your post in one per question, so we can individually vote on them.
If I’ve added overloads of the copy constructor and the copy assignment operator to enable my class for move semantics, are there circumstances where move semantics will not be applied (such as when a std::vector gets resized) because of a missing noexcept keyword?
What is our idiom for using noexcept and or throw in C++0x/11 in general and with regard to move semantics and perfect forwarding in particular?
References: n2983, n3050, n3248, n3279.
Rvalue References And Exceptions
http://thbecker.net/articles/rvalue_references/section_09.html
@Vincent I think the most obvious place for attributes is not in replacing pragmas, but replacing VC++’s __declspec and GCC’s __attribute__.
C++11 has a new feature called attributes. Do you think it’s attractive enough that compiler vendors (e.g., Visual C++) will define their own compiler-defined attributes? What kind of places that third-party attributes can be most useful? Will it replace some of the pragma directives (say in Visual C++)? Thanks.
Can you probably estimate the time needed that Visual C++ will support C++11? Will VC++ 2012 fully (well, almost fully) support C++11? Or will VC++ 2014? Thanks.
Which non-C++ language do you find to be the most inspiring today? Are there any features in that language that you’d like to see in future C++ incarnations?
A vague topic: anything you can tell us in advance about better alignment support, for exemple aligned_Allocator? Hints, people names, blogs; anything.
* There seemed to be some controversy over noexcept on destructors. Your books describe your reasoning on why destructors should never throw. What does the opposition consider to be a valid use of throwing destructors?
* Concepts — why did they fail and what work is being done to bring something like them back?
* Verbose lambdas — The lambdas we have right now are very nice, but verbose compared to C#’s. Polymorphic lambdas could have helped solved this — again, why did they fail and what work is being done to bring something like them back?
* Filesystem — something like boost::filesystem is desperately needed.
* I/O and Async — something like boost::asio is needed, but that’s still a bit unwieldy on the async part — language integration like C#’s async would be even better. any thoughts on this?
* Threading — thread pools, fine-grained task model, thead-safe containers.
What is on the top of your post C++0x wishlist?