在C++ 11中是否支持try/catch/finally构造?
我问,因为我找不到任何关于它的信息.谢谢.
好吧,如果我使用RAII惯用语来管理某些上下文属性*,如果我在try块的开头裸体使用它,它是否会像我期望的那样工作?
换句话说,如果我有这个:
struct raii {
raii() {
std::cout << "Scope init"
<< std::endl; }
~raii() {
std::cout << "Scope exit"
<< std::endl; }
};
Run Code Online (Sandbox Code Playgroud)
......我成功地使用它:
{
raii do_the_raii_thing;
stuff_expecting_raii_context();
/* … */
}
Run Code Online (Sandbox Code Playgroud)
...如果我这样做,RAII实例将以相同的方式工作:
try {
raii do_the_raii_thing;
stuff_expecting_raii_context_that_might_throw();
/* … */
} catch (std::exception const&) {
/* … */
}
Run Code Online (Sandbox Code Playgroud)
这可能是一个愚蠢的问题,但我想在此检查自己的理智 - 我对noexcept保证的微妙之处以及其他与例外相关的细节感到模糊- 所以请原谅我的天真
[*]对于那些好奇的人来说,这是我在RAII管理的Python C-API狡猾的GIL(全球翻译锁),在我的具体案例中
[编辑:(从评论中复制)事实证明,问题出在其他地方,但谢谢大家的意见.]
我有一个共享容器类,它使用一个互斥锁来锁定push()和pop()函数,因为我不想同时修改head和tail.这是代码:
int Queue::push( WorkUnit unit )
{
pthread_mutex_lock( &_writeMutex );
int errorCode = 0;
try
{
_queue.push_back( unit );
}
catch( std::bad_alloc )
{
errorCode = 1;
}
pthread_mutex_unlock( &_writeMutex );
return errorCode;
}
Run Code Online (Sandbox Code Playgroud)
当我在调试模式下运行它时,一切都很好.当我在发布模式下运行时,我大致在驱动程序开始推送和"同时"弹出时崩溃.如果try/catch块捕获到std :: bad_alloc异常,它会立即强制退出吗?如果是这样,我应该将函数的其余部分包含在finally块中吗?
此外,较慢的调试模式是否可能成功,因为我的push()和pop()调用从未实际发生过?
假设有这样一个类:
class A {
private:
QFile file;
public:
A::A(QFile file): file(file) {}
void doSomething() {
file.open(QIODevice::WriteOnly);
// ... do operations that can throw an exception
file.close();
}
}
Run Code Online (Sandbox Code Playgroud)
如果发生某些事情, close() 永远不会调用它。正确的方法是使用 try - finally,但 C++ 不支持它:
class A {
private:
QFile file;
public:
A::A(QFile file): file(file) {}
void doSomething() {
file.open(QIODevice::WriteOnly);
try {
// ... do operations that can throw an exception
}
finally {
file.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能在C++上做到这一点?
class Date {
Date(int day, int month, int year) {
}
}
int main() {
Date d = Date(100, 2, 1990);
}
Run Code Online (Sandbox Code Playgroud)
这里传递给day的值(100)不对,我的问题是如何在构造函数中检查'day'参数以防止创建对象
我们在代码中使用try catch块。我想问的是,使用finally块是一种好习惯。我还没看到多少最终会阻塞代码。这是不好的做法吗?