如何在C ++中创建临时对象 [英] How to create temporary object in C++

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

问题描述

我有以下代码。

class A {
 public:
  A(int) {
  }
};

int a;
int main() {
  A(a);  // Line 'a
  return 0;
}

我想在行'a上做一个是创建一个临时 A 与构造函数 A :: A(int)。我知道它会立即毁灭。这就是我想要的。但似乎编译器正在做类似于 A a ,定义变量 a > A 并使用构造函数 A :: A()初始化它。当然,它不存在,因此编译器错误。

What I want to do on line 'a is to create a temporary A with constructor A::A(int). I know it's going to destruct immediately. That's what I want. But it seems the compiler is doing something equivalent to A a, defining variable a as of class A and initialize it using constructor A::A(). Of course it doesn't exist, hence the compiler error.

但是,如果我将我的代码更改为以下。

However, if I change my code to the following.

class A {
 public:
  A(int) {
  }
};

void f(A) {
}

int a;
int main() {
  f(A(a));
  return 0;
}

编译器构造一个临时 A ,并使用它来调用 f

It works fine now. The compiler constructs a temporary A and use it to call f.

为什么 A(a)在这两种情况下都不同?如何在标准中说明或一些模糊的原因?如何在第一个代码示例中构造一个临时对象?

Why is A(a) different in both contexts? How is it stated in the standard or for some obscure reason? How can I construct a temporary object as in the first code sample?

推荐答案

这是声明是一个声明规则。 [stmt.ambig] / p1:

This is another instance of the "everything that can be a declaration is a declaration" rule. [stmt.ambig]/p1:


语法中含有 expression-statement s
和声明:具有函数式
显式类型转换(5.2.3)的表达式语句作为其最左子表达式可以是
声明,其中第一个声明

There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion (5.2.3) as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration.

标准提供以下示例:


假设T是一个简单类型说明符,

T(a)->m = 7;       // expression-statement
T(a)++;            // expression-statement
T(a,5)<<c;         // expression-statement
T(*d)(int);        // declaration
T(e)[5];           // declaration
T(f) = { 1, 2 };   // declaration
T(*g)(double(3));  // declaration


$ b b

在上面的最后一个例子中, g 是指向 T 的指针,初始化为
double(3)。这当然是由于语义原因而形成的,但
不会影响语法分析。

In the last example above, g, which is a pointer to T, is initialized to double(3). This is of course ill-formed for semantic reasons, but that does not affect the syntactic analysis.


class T {
// ...
public:
    T();
    T(int);
    T(int, int);
};

T(a);          // declaration
T(*b)();       // declaration
T(c)=7;        // declaration
T(d),e,f=3;    // declaration
extern int h;
T(g)(h,2);     // declaration


消除歧义的最简单的方法可能是额外的集合的括号。 (A(a)); 是明确的表达式语句

The simplest way to disambiguate is probably an extra set of parentheses. (A(a)); is unambiguously an expression-statement.

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

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