我正在从C转换到C++.在C++中,malloc函数有用吗?或者我可以使用"new"关键字声明它.例如:
class Node
{
...
}
...
Node *node1 = malloc(sizeof(Node)); //malloc
Node *node2 = new Node; //new
Run Code Online (Sandbox Code Playgroud)
我应该使用哪一个?
是否可以使用malloc?将一些参数传递给另一个类的构造函数中的类的构造函数?我可以这样做new.我需要做同样的事情malloc:(如果它没有意义,考虑我使用自定义分配器而不是malloc)
Class A_Class ... {
public:
B_Class *b;
...
A_Class: ...
{ b = new B_Class (c1, c2, c3);
} // end of constructor
}
Run Code Online (Sandbox Code Playgroud)
现在使用malloc:
Class A_Class ... {
public:
B_Class *b;
...
A_Class: ...
{ b = (B_Class*) malloc (sizeof(*b));
??????????????? }
}
Run Code Online (Sandbox Code Playgroud) 我试图使用g ++ 5.1编译和执行这个小的c ++代码,它编译得很好,当我执行它时,linux我得到这个错误消息:" Segmentation fault (core dumped)".
但是相同的代码在osx上正确运行但在linux上没有运行:
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node {
std::string data;
};
int main() {
struct node * node = (struct node * )
malloc(sizeof(struct node));
node->data.assign("string");
// node->data = "string" --> same issue
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我尝试了一个简单的assigne(node-> data ="string"),但我遇到了同样的问题请帮忙!
我一直试图在不需要时不初始化内存,并且正在使用malloc数组来这样做:
这是我运行的:
#include <iostream>
struct test
{
int num = 3;
test() { std::cout << "Init\n"; }
~test() { std::cout << "Destroyed: " << num << "\n"; }
};
int main()
{
test* array = (test*)malloc(3 * sizeof(test));
for (int i = 0; i < 3; i += 1)
{
std::cout << array[i].num << "\n";
array[i].num = i;
//new(array + i) i; placement new is not being used
std::cout << array[i].num << "\n";
}
for (int i = 0; i …Run Code Online (Sandbox Code Playgroud) c++ ×4
malloc ×3
constructor ×2
new-operator ×2
allocation ×1
assign ×1
destructor ×1
memory ×1
pointers ×1