如何禁止临时 [英] How to disallow temporaries

查看:161
本文介绍了如何禁止临时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于类Foo,有没有办法禁止构造它而不给它一个名称?



例如:

  Foo(hi); 

只有在您给它一个名称时,才允许使用它,如下所示?

  Foo my_foo(hi); 

第一个的生命周期只是语句,第二个是封闭的块。在我的用例中, Foo 正在测量构造函数和析构函数之间的时间。因为我从来没有提到局部变量,我经常忘记把它,并意外改变了生命。

解决方案

另一个基于宏的解决方案:

  #define Foo class Foo 

语句 Foo(hi); 扩展为 class Foo(hi); 形成;但 Foo a(hi)扩展为 class Foo a(hi) / p>

这有一个优点,就是它与源代码和二进制兼容现有的(正确的)代码。 (此声明不完全正确 - 请参阅Johannes Schaub的评论,然后进行以下讨论:如何知道它与源代码兼容现有代码?他的朋友包括他的标题和void f(){ int Foo = 0;}以前编译的精细和现在的错误编译!另外,定义一个成员函数Foo类的每一行失败:void class Foo :: bar(){} p>

For a class Foo, is there a way to disallow constructing it without giving it a name?

For example:

Foo("hi");

And only allow it if you give it a name, like the following?

Foo my_foo("hi");

The lifetime of the first one is just the statement, and the second one is the enclosing block. In my use case, Foo is measuring the time between constructor and destructor. Since I never refer to the local variable, I often forget to put it in, and accidentally change the lifetime. I'd like to get a compile time error instead.

解决方案

Another macro-based solution:

#define Foo class Foo

The statement Foo("hi"); expands to class Foo("hi");, which is ill-formed; but Foo a("hi") expands to class Foo a("hi"), which is correct.

This has the advantage that it is both source- and binary-compatible with existing (correct) code. (This claim is not entirely correct - please see Johannes Schaub's Comment and ensuing discussion below: "How can you know that it is source compatible with existing code? His friend includes his header and has void f() { int Foo = 0; } which previously compiled fine and now miscompiles! Also, every line that defines a member function of class Foo fails: void class Foo::bar() {}")

这篇关于如何禁止临时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆