C ++中new运算符的用途是什么? [英] What's the use of new operator in c++?

查看:81
本文介绍了C ++中new运算符的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以像下面的示例中那样使用一个简单的对象来应用new吗?

Can we apply new like in the example below with a simple object?

class x
{
    public:
         x()
         {
             cout<<"Default constructor";
         }
         ~x()
         {
             cout<<"Destructor called";
         }
};

int main()
{
    x o = new x();
    getch();
    return 0;
}

推荐答案

否.
new x()


返回指向新创建对象的x *(指向x对象的指针).

正确的方法是


returns an x* (a pointer to an x object) that points-to the newly created object.

the correct way to to that is

int main()
{
   //creates a new default-constructed x, giving its
   //address back to px
   x* px = new x(); 
  
   //calls x::~x() on the object pointed by px,
   //and return teh memory to the system.
   delete px;
  
   //wait for a key (not hortodox, but may be needed)
   getch();
}



或者,您可以使用
将x对象作为函数局部变量实例化到堆栈中.



Alternativelly, you can instantiate an x object into the stack as a function local variable with

int main()
{
   x o; //create a default constructed x into the stack
   getch(); //wait for a kay
} //here o is destroyed.



请注意,如果运行此程序,o似乎不会被破坏,因为它的破坏发生在getch()之后. 要查看其实际工作,请从打开的命令提示符处调用它:
它将打印



Note that if you run this program, o will seem not destroyed, since its destruction happens after getch().
To see its real work, invoke it from an opened command prompt:
it will print

Default constructor will wait for a keypress here
Destructor called



请注意,还应该在已打印的消息上放置endl,否则消息本身直到找到endl才可以打印,要使用的cout 需要包含std的名称空间,cout要求< iostream>

这样可以得到一个完整的样本



Note that you should also place an endl on the printed message, otherwise the message themselves could be not printed until an endl is found, that cout to be usedrequire the std namespace to be included, that cout requires <iostream>

So a complete sample can be

#include <iostream>

class x
{
public:
     x()
     {
         std::cout<<"Default constructor"<<std::endl;
     }
     ~x()
     {
         std::cout<<"Destructor called"<<std::endl;
     }
};

// main woarking with dynamic memory

int main()
{
    x* o = new x();
    getch();
    delete o;
    return 0;
}

//alternative main, working on stack

int main()
{
    x o;
    getch();
    return 0;
}



只能使用main的两个变体之一.



use only one of the two variants of main.


由于程序无法编译,因此"new"没有用处.编译器抱怨:错误C2440:正在初始化":无法从"x *"转换为"x"

您声明类型为x的对象"o".这足以实例化该类.然后使用"new"实例化该类的另一个对象.

现在,您不能做的就是将对对象的引用(结果为"new")存储到该类的变量中,而不是指向该类的指针. "x * o = new x();"将是执行此操作的正确方法.

因此,要么声明该类的变量:

x o;

或声明指向该类的指针并使用new创建实例:

x * o = new x();

但是不要混在一起
Since the program doesn''t compile, there is no use for "new". The compiler complains : error C2440: ''initializing'' : cannot convert from ''x *'' to ''x''

You declare an object "o" of type x. That''s enough to instantiate the class. Then you use "new" to instantiate another object of the class.

Now what you cannot do is store the reference to the object (result of "new") into a variable that is of the class and not a pointer to the class. "x *o = new x();" would be the proper way to do this.

So, either declare a variable of the class:

x o;

or declare a pointer to the class and create the instance with new:

x *o = new x();

but don''t mix them


简单的答案是肯定的.
但是,您有内存泄漏.您正在分配对象o,但不释放其内存.
The simple answer is yes.
You have a memory leak however. You are allocating the object o, but not releasing its memory.
int main()
{
    x o = new x();
    getch();
    delete o; //this will call ~x()
    return 0;
}



现在回答主题中的问题.

new/delete有很多用途.

首先是动态内存分配.所有这些都与malloc/free函数完全相同:
当处理动态大小的数据(例如文件的内容)时,使用堆栈是不切实际的,因为您不知道文件的大小.



Now to answer the question in the topic.

new/delete has many uses.

Firstly dynamic memory allocation. All of this is exactly the same as the malloc/free functions:
When dealing with dynamic size data (for example the contents of a file) it is not practical to use the stack, because you have no idea how big the file will be.

//This allocates 1KB on the stack to store the contents of the file.
//If the file is bigger than 1KB this is going to cause issues
char file_buffer[1024];
//instead you would use
int file_size = /*...*/; //get the size of the file somehow
char *file_buffer = new char[file_size];



通常,当处理大量内存时,可以使用new/deletemalloc/free堆.您的程序的堆栈空间有限(尽管通常很大).如果堆栈用完,程序将突然崩溃.至少如果堆用完了,malloc将返回null或new将引发异常,您都可以根据需要处理这两个异常.

现在说明new/deletemalloc/free中的区别.
new调用构造函数,delete调用析构函数. malloc/free不要.

new在分配时自动获取正确的数据大小.



Typically when dealing with large amounts of memory you would use the heap, with new/delete or malloc/free. Your program has limited (although usually quite large) stack space. If you run out of stack your program will crash abruptly. At least if you run out of heap malloc will return null or new will thrown an exception, both of which you can handle as needed.

Now for the differences in new/delete and malloc/free.
new calls the constructor, delete calls the destructor. malloc/free don''t.

new automatically gets the correct data size when allocating.

int *numbers = (int *)malloc(10 * sizeof(int));
//is the same as
int *numbers = new int[10];



使用new分配数组时,必须使用delete[]



When allocating an array with new, you must use delete[]

int *numbers = new int[10];
delete[] numbers;


这篇关于C ++中new运算符的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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