[英]Temporary objects in C and C++
C code C代码
#include <stdio.h>
typedef struct
{
int a;
}A;
int main()
{
A(); // this line gives error
return 0;
}
Output Output
Error: Expected identifier or '('
C++ code C++代码
#include <iostream>
struct A
{
int a;
A()
{
std::cout<<"Ctor-A\n";
}
~A()
{
std::cout<<"Dctor-A\n";
}
};
int main()
{
A(); // creates temporary object and destroyed it
return 0;
}
Output Output
Ctor-A
Dctor-A
I know about the "Rule of three", but code becomes complicated and most compilers don't give errors if we don't follow the rule.我知道“三规则”,但代码会变得复杂,如果我们不遵守规则,大多数编译器都不会给出错误。 So I avoided creation of a copy constructor and an overloaded assignment operator.
所以我避免创建复制构造函数和重载赋值运算符。
Why does A()/A{}
create a temporary object in C++, but not in C?为什么
A()/A{}
在C++中创建了一个临时的object,而在C中却没有? What's another way to create a temporary object in C?在 C 中创建临时 object 的另一种方法是什么?
In C (C99 and later) you can create a structure with automatic lifetime using a Compound Literal .在 C(C99 及更高版本)中,您可以使用复合文字创建具有自动生命周期的结构。
The syntax is (A){ initializers, for, struct, members }
.语法是
(A){ initializers, for, struct, members }
。
The lifetime is automatic, not temporary, so the structure created in this way does not vanish at the end of the full-expression, but at the end of the enclosing scope.生命周期是自动的,不是临时的,所以以这种方式创建的结构不会在完整表达式结束时消失,而是在封闭的 scope 结束时消失。
This expression这个表情
A()
is considered by C compilers as a function call.被 C 编译器视为 function 调用。 In C++ such an expression means a call of a constructor provided that A is a class type.
在 C++ 这样的表达式意味着调用构造函数,前提是 A 是 class 类型。
To create a temporary object in C you could declare a function like for example要在 C 中创建临时 object,您可以声明一个 function,例如
struct A { int a; } A( int x )
{
struct A a = { .a = x };
return a;
}
and then you can call the function creating a temporary object of the type struct A like然后你可以调用 function 创建一个类型为 struct A 的临时 object
A( 10 );
Here is a demonstrative program.这是一个演示程序。
#include <stdio.h>
struct A { int a; } A( int x )
{
struct A a = { .a = x };
return a;
}
int main(void)
{
struct A a = A( 10 );
printf( "a.a = %d\n", a.a );
return 0;
}
The program output is程序 output 是
a.a = 10
A()
calls the constructor for the struct A in the C++ code. A()
在 C++ 代码中调用结构 A 的构造函数。 However, C doesn't support constructors / destructors, or even objects (in the sense of OOP) in fact.但是,C 实际上不支持构造函数/析构函数,甚至不支持对象(在 OOP 的意义上)。 The only way to create a temporary object as you describe in C would be to declare a variable of type A and wait for it to go out of scope, where the memory allocated for it will be popped from the stack, or to allocate a variable on the heap and free it in the next line.
如您在 C 中所述,创建临时 object 的唯一方法是声明类型 A 的变量并等待它从 scope 变为 go,其中为其分配的 memory 将从堆栈中弹出,或分配一个变量在堆上并在下一行释放它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.