为什么在 C++ 中有这么多不同的方式使用 new 运算符?

发布于 2024-11-06 22:18:13 字数 1007 浏览 1 评论 0原文

我刚刚阅读了cplusplus.com 上的新运算符说明。该页面给出了一个示例来演示使用 new 运算符的四种不同方法,如下所示:

// operator new example
#include <iostream>
#include <new>
using namespace std;

struct myclass {myclass() {cout <<"myclass constructed\n";}};

int main () {

   int * p1 = new int;
// same as:
// int * p1 = (int*) operator new (sizeof(int));

   int * p2 = new (nothrow) int;
// same as:
// int * p2 = (int*) operator new (sizeof(int),nothrow);

   myclass * p3 = (myclass*) operator new (sizeof(myclass));
// (!) not the same as:
// myclass * p3 = new myclass;
// (constructor not called by function call, even for non-POD types)

   new (p3) myclass;   // calls constructor
// same as:
// operator new (sizeof(myclass),p3)

   return 0;
}

我的问题是:

  1. 使用的最佳实践是什么 新运营商?
  2. myclass* p3 = new myclass 是否等同于 myclass* p3 = new myclass()

I've just read the new operator explanation on the cplusplus.com. The page gives an example to demonstrate four different ways of using new operator as following:

// operator new example
#include <iostream>
#include <new>
using namespace std;

struct myclass {myclass() {cout <<"myclass constructed\n";}};

int main () {

   int * p1 = new int;
// same as:
// int * p1 = (int*) operator new (sizeof(int));

   int * p2 = new (nothrow) int;
// same as:
// int * p2 = (int*) operator new (sizeof(int),nothrow);

   myclass * p3 = (myclass*) operator new (sizeof(myclass));
// (!) not the same as:
// myclass * p3 = new myclass;
// (constructor not called by function call, even for non-POD types)

   new (p3) myclass;   // calls constructor
// same as:
// operator new (sizeof(myclass),p3)

   return 0;
}

My questions are:

  1. What is the best practice of using
    new operator?
  2. Is myclass* p3 = new myclass equivalent to myclass* p3 = new myclass()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

瑕疵 2024-11-13 22:18:13

因为他们有不同的目的。如果您不希望 new 在失败时抛出 std::bad_alloc,则可以使用 nothrot。如果您想在现有存储中分配对象,您可以使用placement new……如果您想要原始的、未初始化的内存,您可以直接调用operator new并将结果转换为目标类型。

在 99% 的情况下,new 的简单标准用法是 MyClass* c = new MyClass();

对于你的第二个问题:< code>new Object() 与 new Object 形式通常并不相同。请参阅此问题和回复 详细信息。但这确实是吹毛求疵。通常它们是等效的,但为了安全起见,总是选择 new Object();请注意,在这个特定的示例中,它们是相等的,因为 MyClass 没有任何成员,所以严格来说,您的问题的答案是肯定的。

Because they have different purposes. If you didn't want new to throw std::bad_alloc on failure, you would use nothrow. If you wanted to allocate your objects in existing storage, you would use placement new … if you want raw, uninitialized memory, you would invoke operator new directly and cast the result to the target type.

The plain standard usage of new in 99% of all cases is MyClass* c = new MyClass();

To your second question: the new Object() vs. new Object forms are not generally equal. See this question and the responses for the details. But that really is nitpicking. Usually they are equivalent, but to be on the safe side always pick new Object(); Note that, in this particular sample they are equal because MyClass doesn't have any members, so strictly speaking the answer to your question is yes.

万劫不复 2024-11-13 22:18:13

1) 其中一些仅在特定的、不寻常的情况下使用。无论如何,大多数时候,普通的传统传统方式是最好的:

X * x = new X();

2)是的,它们是。如果构造函数没有参数,则括号是可选的。如果你声明一个自动变量——也就是说,

X x;

必须省略括号,否则它就是一个函数声明!因此,许多人会告诉您在 new 表达式中也省略它们。我认为这是一个很好的做法,但我只是习惯了将它们包括在内。

1) Several of these are used only in specific, unusual situations. The plain old traditional one is best, most of the time anyway:

X * x = new X();

2) Yes, they are. If the constructor has no arguments, the parentheses are optional. If you're declaring an automatic variable -- i.e.,

X x;

then you must omit the parentheses, or it's a function declaration! As a result, many people will tell you to omit them in the new expression as well. That's a good practice, I think, but I'm just used to including them.

焚却相思 2024-11-13 22:18:13

您在不同的情况下需要它们,而不是“最佳实践”。例如,大多数人只想调用 new x() 来分配一些内存并创建对象。但是,有时您不希望在 new 失败时引发异常,因此您可以调用 new (nothrot) 来获取 null 返回。

如果您已经分配了一些内存但需要创建对象,则可以通过调用 new (p3) x 来使用“placement new”。

在极少数情况下,您需要使用类的内存分配器但实际上并不创建对象,您可以使用 (myclass*) operator new (sizeof(myclass)) 语法。

Rather than "best practice", you need them in different situations. For example, most people just want to call new x() to allocate some memory and create the object. However, sometimes you're in situations where you don't want an exception thrown in case new fails, so you call new (nothrow) instead to get a null back.

If you already have some memory allocated but need to create an object, you use "placement new" by calling new (p3) x.

In the rare case where you need to use a class's memory allocator but not actually create an object, you use the (myclass*) operator new (sizeof(myclass)) syntax.

拥醉 2024-11-13 22:18:13

以下是我的建议:

  1. 最好不要使用 new;路过
    可以的时候参考一下。 (避免内存泄漏)。
  2. 使用operator newx = new X(); // 记住使用delete
  3. 优先选择std::vector 而不是数组new
    x = new X()[数量]; // 记得使用delete[]
  4. 不要使用placement new除非
    你绝对知道原因。

一般来说,placement new 用于从特定地址或特殊内存池进行分配。这是一个高级主题。

Here are my recommendations:

  1. Prefer not to use new; pass by
    reference when possible. (Avoids memory leaks).
  2. Use operator new: x = new X(); // Remember to use delete
  3. Prefer std::vector to array new:
    x = new X()[quantity]; // Remember to use delete []
  4. Don't use placement new unless
    you absolutely know the reasons.

In general, placement new is used to allocate from specific addresses or a special memory pool. This is an advanced topic.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文