[英]How to create object in heap without using new operator in c++?
new
operator in C++ is used for creating new objects in heap memory. I have no idea if how to create object in heap memory without using new operator. C++ 中的
new
运算符用于在堆 memory 中创建新对象。我不知道如何在不使用新运算符的情况下在堆 memory 中创建 object。 Is it possible, and how?有可能吗,怎么办?
Also can anyone also suggest me creating object in stack using new
opeartor in C++?也有人可以建议我在 C++ 中使用
new
的 opeartor 在堆栈中创建 object 吗?
In my limited experience with C++, Using new operator is the only way to create common object in heap. 以我有限的C ++经验,使用new运算符是在堆中创建公共对象的唯一方法。 HeapAlloc can allocate memory in heap, but how can you create a class in heap without using new operator?
HeapAlloc可以在堆中分配内存,但是如何在不使用new运算符的情况下在堆中创建类?
In modern C++
it is common to avoid using new
directly by using the functions, std::make_unique and std::make_shared which return smart pointers . 在现代
C++
,通常避免通过使用返回智能指针的函数std :: make_unique和std :: make_shared直接使用new
。
Eg. 例如。
class Object
{
public:
Object(int i): i(i) {}
// ...
void do_stuff() { /*...*/ }
private:
int i;
};
auto object = std::make_unique<Object>(4);
object->do_stuff();
Now you don't have to worry about deleting object
. 现在,您不必担心删除
object
。
To answer one of your questions, you can use placement new to allocate objects on the stack. 要回答您的问题之一,可以使用new放置在堆栈上分配对象。 For example:
例如:
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;
}
you can use c language in c++ to create objects without using the new keyword.You can create a pointer to allocate to an address in heap memory using malloc:您可以在 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.