gpt4 book ai didi

c++ - 巧妙破坏的 C++ 代码的邪恶样本

转载 作者:IT老高 更新时间:2023-10-28 12:30:33 26 4
gpt4 key购买 nike

我需要一些不良 C++ 代码示例来说明违反良好做法的情况。我想提出我自己的例子,但我很难提出不是人为的例子,并且陷阱不是立即显而易见的(这比看起来更难)。

示例如下:

  1. 不为具有 std::auto_ptr 成员的类定义复制构造函数,并使用具有前向声明类的 std::auto_ptr 成员。
  2. 从构造函数或析构函数(直接或间接)调用虚函数。
  3. 重载模板函数。
  4. 带有 boost::shared_ptr 的循环引用。
  5. 切片。
  6. 从 C 回调中抛出异常(直接或间接)。
  7. 等式的浮点比较。
  8. 具有原始指针成员的构造函数的异常安全性。
  9. 从析构函数中抛出。
  10. 在不同架构上编译时整数溢出(size_tint 不匹配)。
  11. 使容器迭代器失效。

...或者你能想到的任何其他邪恶的东西。

我会很感激一些关于现有资源的指针,或者一两个示例。

最佳答案

The most vexing parse这是 C++ 解析这样的事情的方式的一个惊人的违反直觉的结果:

// 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

这会让任何不熟悉这种语言的特殊怪癖的人(包括我开始学习 C++ 时)感到惊讶。

关于c++ - 巧妙破坏的 C++ 代码的邪恶样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4295681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com