下面显示的代码不应该编译

下面显示的代码不应该编译

本文介绍了根据C ++社区中一个知识渊博的作者,下面显示的代码不应该编译。他错了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Herb Sutter下面的代码不会编译。查看此网站其中我提取了以下文本,关于 function-try-blocks

According to Herb Sutter the code below wouldn't compile. See this site http://www.gotw.ca/gotw/066.htm from where I've extracted the following text, regarding function-try-blocks :

顺便说一句,这也意味着唯一一个(重复
)可能用于构造函数 - try -block是
翻译从基础或成员子对象抛出的异常。这是
道德#1。接下来,道德#2说析构函数 - 尝试块是
完全使用 -

Incidentally, this also means that the only (repeat only) possible use for a constructor function-try-block is to translate an exception thrown from a base or member subobject. That's Moral #1. Next, Moral #2 says that destructor function-try-blocks are entirely usele--

- 但是等待!我听到有人从房间中间打断了。
我不同意道德#1,我可以想到另一个可能用于
构造函数的功能块,即释放资源分配在
的初始化列表或在构造函数体!

"--But wait!" I hear someone interrupting from the middle of the room. "I don't agree with Moral #1. I can think of another possible use for constructor function-try-blocks, namely to free resources allocated in the initializer list or in the constructor body!"

对不起,不行。毕竟,记住,一旦你进入你的
构造函数try-block的处理程序,
构造函数体中的任何局部变量也已经超出范围,你保证
没有基本子对象或成员对象再存在,周期。你
甚至不能引用他们的名字。你的对象的部分是
从来没有被构造,或那些被构造已经被
销毁。所以你不能清理依赖
引用一个基类或类的成员的任何东西(反正,这是
的基础和成员析构函数,对吗?)。

Sorry, nope. After all, remember that once you get into your constructor try-block's handler, any local variables in the constructor body are also already out of scope, and you are guaranteed that no base subobjects or member objects exist any more, period. You can't even refer to their names. Either the parts of your object were never constructed, or those that were constructed have already been destroyed. So you can't be cleaning up anything that relies on referring to a base or member of the class (and anyway, that's what the base and member destructors are for, right?).

假设这个引用,下面的代码不应该编译,因为 cat 在进程运行到 catch 子句中时被破坏。但它是,至少与VSC2008。

Assuming this quote, the following code should not compile, as the object cat has already been destructed by the time the process runs into the catch clause. But it does, at least with VSC2008.

class Cat
{
    public:
    Cat() { cout << "Cat()" << endl; }
    ~Cat() { cout << "~Cat()" << endl; }
};

class Dog
{
    public:
    Dog() { cout << "Dog()" << endl; throw 1; }
    ~Dog() { cout << "~Dog()" << endl; }
};


class UseResources
{
    class Cat *cat;
    class Dog dog;

    public:
    UseResources();
    ~UseResources() { delete cat; cat = NULL; cout << "~UseResources()" << endl; }
};

UseResources::UseResources() try : cat(new Cat), dog() { cout << "UseResources()" << endl; } catch(...)
{
    delete cat;
    throw;
}


推荐答案

Sutter实际上是说它不会编译。他只是解释标准对情况(15.3.10)的后果:

I don't think Herb Sutter is actually saying that it won't compile. He is just explaining the consequences of what the standard has to say about the situation (15.3.10):

这篇关于根据C ++社区中一个知识渊博的作者,下面显示的代码不应该编译。他错了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:49