C ++ 98和C ++ 11之间的变化表明行为有何不同?

时间:2017-10-09 15:47:53

标签: c++11 language-lawyer c++98

我正在阅读以下帖子:

以及isocpp页面:

根据标准,我变得很好奇:C ++ 11中引入的哪些更改可能会破坏用C ++ 98编写的程序?

2 个答案:

答案 0 :(得分:2)

最突出的一个 - 从析构函数中抛出异常。

在C ++ 98中,你可以拥有执行此操作的程序,如果你小心的话,可以正常工作。

在C ++ 11中,您经常需要明确声明dtor noexcept(false)

很好blog post here,关于Andrzej的C ++博客。

  

简而言之,以下程序用于在C ++ 03中成功运行(在“成功”的某些定义下):

struct S
{
  ~S() { throw runtime_error(""); } // bad, but acceptable
}; 

int main()
{
  try { S s; }
  catch (...) {
    cerr << "exception occurred";
  } 
  cout << "success";
}
     

在C ++ 11中,同一程序将触发对std::terminate的调用。

答案 1 :(得分:0)

这是与C ++ 11中的析构函数相关的另一种情况:noexcept(true):

// A simple program that demonstrates how C++11 and pthread_cancel don't play
// nicely together.
//
// If you build without C++11 support (g++ threadkill.cpp -lpthread), the
// application will work as expected. After 5 seconds, main() will cancel the
// thread it created and the program will successfully exit.
//
// If you build with C++11 support(g++ -std=c++11 threadkill.cpp -lpthread),
// the program will crash because the abi::__forced_unwind exception will
// escape the destructor, which is implicitly marked as noexcept(true) in
// C++11. If you mark the destructor as noexcept(false), the program does 
// not crash.
#include <iostream>
#include <unistd.h>
#include <string.h>

class sleepyDestructorObject
{
public:
    ~sleepyDestructorObject() //noexcept(false)
    {
        std::cout << "sleepy destructor invoked" << std::endl;
        while(true)
        {
            std::cout << "." << std::flush;
            sleep(1);
        }
    }
};

void* threadFunc( void* lpParam )
{
    sleepyDestructorObject sleepy;
    return NULL;
}

int main(int argc, char** argv)
{
    pthread_t tThreadID;
    pthread_create(&tThreadID, NULL, threadFunc, NULL);
    sleep(5);
    pthread_cancel(tThreadID);
    pthread_join(tThreadID, NULL);
    return 0;
}

原始参考: