C++ 创建没有“new”运算符的类的新实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5885634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create new instance of a class without "new" operator
提问by Sam
Just a simple question. As the title suggests, I've only used the "new" operator to create new instances of a class, so I was wondering what the other method was and how to correctly use it.
只是一个简单的问题。正如标题所暗示的,我只使用了“new”运算符来创建类的新实例,所以我想知道其他方法是什么以及如何正确使用它。
回答by Nawaz
You can also have automaticinstances of your class, that doesn't use new
, as:
您还可以拥有不使用的类的自动实例new
,例如:
class A{};
//automatic
A a;
//using new
A *pA = new A();
//using malloc and placement-new
A *pA = (A*)malloc(sizeof(A));
pA = new (pA) A();
//using ONLY placement-new
char memory[sizeof(A)];
A *pA = new (memory) A();
The last two are using placement-newwhich is slightly different from just new. placement-new is used to construct the object by calling the constructor. In the third example, malloc
only allocates the memory, it doesn't call the constructor, that is why placement-newis used to call the constructor to construct the object.
最后两个使用位置,新的是从稍稍不同的新的。placement-new 用于通过调用构造函数来构造对象。在第三个例子中,malloc
只分配内存,不调用构造函数,这就是为什么使用placement-new来调用构造函数来构造对象。
Also note how to delete the memory.
还要注意如何删除内存。
//when pA is created using new
delete pA;
//when pA is allocated memory using malloc, and constructed using placement-new
pA->~A(); //call the destructor first
free(pA); //then free the memory
//when pA constructed using placement-new, and no malloc or new!
pA->~A(); //just call the destructor, that's it!
To know what is placement-new, read these FAQs:
要了解什么是新展示位置,请阅读以下常见问题解答:
- What is "placement new" and why would I use it?(FAQ at parashift.com)
- placement new(FAQ at stackoverflow.com)
- 什么是“placement new”,我为什么要使用它?(parashift.com 上的常见问题解答)
- 新位置(stackoverflow.com 上的常见问题解答)
回答by Bj?rn Pollex
You can just declare a normal variable:
你可以只声明一个普通变量:
YourClass foo;
回答by James Kanze
Any of the usual ways: as a local or static variable, or as
a temporary. In general, the only times you use new
in C++ is
when the object has identity and a lifetime which doesn't
correspond to a scope, or when it is polymorphic. (There are
exceptions, of course, but not many.) If the object can be
copied, it's usually preferable to use local instances, copying
those as needed. (Just like you would for int
, in fact.)
任何通常的方式:作为局部或静态变量,或作为临时变量。通常,您new
在 C++ 中使用的唯一时间是对象具有标识和不对应于作用域的生命周期,或者它是多态的。(当然也有例外,但不是很多。)如果对象可以被复制,通常最好使用本地实例,根据需要复制那些。(int
事实上,就像你所做的那样。)
回答by Rikku
Using malloc will give you the same result as new, just without calling the constructor.
使用 malloc 将为您提供与 new 相同的结果,而无需调用构造函数。