[英]How to create object in heap without using new operator in c++?
C++ 中的new
运算符用于在堆 memory 中创建新对象。我不知道如何在不使用新运算符的情况下在堆 memory 中创建 object。 有可能吗,怎么办?
也有人可以建议我在 C++ 中使用new
的 opeartor 在堆栈中创建 object 吗?
以我有限的C ++经验,使用new运算符是在堆中创建公共对象的唯一方法。 HeapAlloc可以在堆中分配内存,但是如何在不使用new运算符的情况下在堆中创建类?
在现代C++
,通常避免通过使用返回智能指针的函数std :: make_unique和std :: make_shared直接使用new
。
例如。
class Object
{
public:
Object(int i): i(i) {}
// ...
void do_stuff() { /*...*/ }
private:
int i;
};
auto object = std::make_unique<Object>(4);
object->do_stuff();
现在,您不必担心删除object
。
要回答您的问题之一,可以使用new放置在堆栈上分配对象。 例如:
int main()
{
using namespace std;
char buf[sizeof(string)]; // allocate char array on stack
string *str = new (buf) string{ "I'm a placement new string object" };
cout << *str << endl;
str->~string(); // delete string object
// character array object will be
// automatically deallocated
return 0;
}
您可以在 c++ 中使用 c 语言创建对象,而无需使用 new 关键字。您可以使用 malloc 创建一个指针以分配到堆 memory 中的地址:
// make sure to include iostream to access the c library so you can use malloc
#include <iostream>
class Rectangle
{
private:
int length;
int breadth;
public:
Rectangle(int l, int b) :length(l), breadth(b)
{
std::cout << "overloaded constructor called!" << std::endl;
}
void set_length(int length)
{
length = length;
}
void set_breadth(int breadth)
{
breadth = breadth;
}
int area() {
return length * breadth;
}
int get_length()
{
return length;
}
int get_breadth()
{
return breadth;
}
};
int main(int argc, char const *argv[])
{
// create a pointer object
Rectangle *ptr;
// allocate object to heap memory using malloc
ptr = (Rectangle *) malloc(sizeof(Rectangle));
ptr->set_length(10);
ptr->set_breadth(15);
printf("length %d\n", ptr->get_length());
printf("breadth %d\n", ptr->get_breadth());
// free up heap memory when done using delete keyword
delete ptr;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.