gpt4 book ai didi

c++ - 试图删除作为指针的模板类型的编译器错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:49:37 24 4
gpt4 key购买 nike

我是 C++ 的新手,我想了解模板的工作原理。所以我实现了一个通用列表 MyList,它可能包含内置的原始类型和指针。在 remove 函数中,我想区分指针类型和内置对象,这样我就可以删除指针后面的对象,但不影响内置对象。

为了区分模板类型,可以是指针或非指针,我编写了以下函数,它们工作正常:

// distinguish between pointer and non-pointer type of template variable
template<typename T> bool is_pointer(T t) {
return false;
}

template<typename T> bool is_pointer(T* t) {
return true;
}

在列表函数 remove 中,想法是测试指针并删除它们以防万一。但是,删除语句无法编译:

template<typename T> void MyList<T>::remove() {
...
if (is_pointer(temp->getContent())) {
// delete object pointer points to
T t = temp->getContent();
cout << t; // prints out address
// delete t; // produces compiler error (see below)
}

main.cpp 中,我测试了各种类型的列表类,我在其他中调用:

MyList<int> mylist;                // with type int
mylist.remove();
mylist.add(3);
// add and remove elements

MyList<string> mylist2; // with type string
...

MyList<string*> mylist3; // with type string*
mylist.add(new string("three"));
mylist.remove();

当我注释掉语句 delete t; 时,我可以验证控制流是否正确:只为 string* 示例输入了 if 语句。但是,如果我取消注释 delete 语句,编译器会这样提示:

../mylist.h: In member function ‘void MyList<T>::remove() [with T = int]’:
../main.cpp:36:18: instantiated from here
../mylist.h:124:6: error: type ‘int’ argument given to ‘delete’, expected pointer
../mylist.h: In member function ‘void MyList<T>::remove() [with T = std::basic_string<char>]’:
../main.cpp:71:18: instantiated from here
../mylist.h:124:6: error: type ‘struct std::basic_string<char>’ argument given to ‘delete’, expected pointer
make: *** [main.o] Error 1

我没看到什么?我仅在指针上使用 delete 语句,但仍然出现这些编译器错误。如果我在 if 语句中打印出 t 它是一个指针地址!

最佳答案

模板是编译器根据蓝图的使用实际创建类型的蓝图。当您将模板与 intstring* 一起使用时,编译器实际上会创建 MyList 的两个变体,将 T 替换为实际类型。对 T 使用 int 的实现是伪造的,因为删除 int 没有意义。编译器生成的实际代码是

int t = temp->getContent();
cout << t;
delete t;

这是不正确的,您可能会发现。

关于c++ - 试图删除作为指针的模板类型的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18891338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com