Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Evil samples of subtly broken C++ code

I need some samples of bad C++ code that will illustrate violation of good practices. I wanted to come up with my own examples, but I am having a hard time coming up with examples that are not contrived, and where a trap is not immediately obvious (it's harder than it seems).

Examples would be something like:

  1. Not defining copy constructor for classes with std::auto_ptr members, and using std::auto_ptr members with forward-declared classes.
  2. Calling virtual functions from a constructor or a destructor (directly or indirectly).
  3. Overloading a template function.
  4. Circular references with boost::shared_ptr.
  5. Slicing.
  6. Throwing exceptions from C callbacks (directly or indirectly).
  7. Floating point comparison for equality.
  8. Exception safety of constructors with raw pointer members.
  9. Throwing from destructors.
  10. Integer overflow when compiled on different architectures (mismatch of size_t and int).
  11. Invalidating a container iterator.

...or any other evil thing you can think of.

I'd appreciate some pointers to existing resources, or a sample or two.

question from:https://stackoverflow.com/questions/4295681/evil-samples-of-subtly-broken-c-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The most vexing parse is an amazingly counterintuitive result of the way C++ parses things like this:

// Declares a function called "myVector" that returns a std::vector<float>.
std::vector<float> myVector(); 
// Does NOT declare an instance of std::vector<float> called "myVector"

// Declares a function called "foo" that returns a Foo and accepts an unnamed
// parameter of type Bar.
Foo foo(Bar()); 
// Does NOT create an instance of Foo called "foo" nor creates a Bar temporary

// Declares a function called "myVector" that takes two parameters, the first named
// "str" and the second unnamed, both of type std::istream_iterator<int>.
std::vector<float> myVector( 
    std::istream_iterator<int>(str),
    std::istream_iterator<int>()
);
// Does NOT create an instance of `std::vector<float>` named "myVector" while copying
// in elements from a range of iterators

This will surprise just about anybody who is not familiar with this particular quirk of the language (myself included when I started learning C++).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...