简体   繁体   English

在模板化类的构造函数中使用malloc

[英]Using malloc in a constructor of a templated class

Let's say I have a class which will be used to create either tree or list structure. 假设我有一个将用于创建树或列表结构的类。 Let's call it 叫它吧

template <typename K, typename V>
class Node{
  // some data
  Node<K,V>* next;
  Node() {
    next = static_cast<Node<K,V>*>( malloc( sizeof(Node<K,V>) ));
  }
};

By doing this I get a following compiler error: 通过这样做,我得到以下编译器错误:

there are no arguments to 'malloc' that depend on a template parameter, so a declaration of 'malloc' must be available (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated) 没有依赖模板参数的'malloc'参数,因此'malloc'声明必须可用(如果您使用'-fpermissive',G ++将接受您的代码,但是不建议使用未声明的名称)

Is there any way to use malloc in such a way without having to use deprecated code? 有什么方法可以使用malloc而不用使用不赞成使用的代码吗? I want to use malloc instead of new because I'd like to do some more advanced memory management up there. 我想用malloc代替new,因为我想在那里做一些更高级的内存管理。

Looks like you are missing #include <cstdlib> or #include <stdlib.h> . 好像您缺少#include <cstdlib>#include <stdlib.h> The compiler is complaining about a missing declaration. 编译器抱怨缺少声明。 Those include files provide one. 那些包含文件提供了一个。

The compiler error is telling you that it does not have a declaration of what malloc is. 编译器错误告诉您它没有声明malloc是什么。 You are missing the include that declares that function. 您缺少声明该功能的包含。

Other than that, the approach is broken. 除此之外,该方法是无效的。 You are writing a generic tree, but because of the use of malloc you are limiting the use to POD types (I am assuming that K and V are stored in the Node ). 您正在编写通用树,但是由于使用了malloc ,因此将使用范围限制到POD类型(我假设KV存储在Node )。 You should use new instead that will call the constructor for the type, not just allocate memory. 您应该使用new代替,它将调用该类型的构造函数,而不仅仅是分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM