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

标签 c++ templates pointers compiler-errors

我是 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/

相关文章:

c++ - 避免内联显式实例化的 std::vector<T> 代码? ( Visual Studio C++ 2008)

c++ - "used without template parameters"

c++ - 具有从属限定标识的类成员 using-declaration 是否应该是从属名称?

带字符串的 C++ 函数指针

c++ - 尝试使用 boost::interprocess::managed_shared_memory::construct<T> 编译应用程序时出错

c++ - 字符串和特殊字符的奇怪现象

c++ - 使用QTextStream C++读取一个txt文件

c++ - 使用子类中的类型定义扩展模板类

c++ - 用 const 限定符更改替换方法 (C++)

c++ - 删除不同位置的指针会导致不同的行为(崩溃与否)