【发布时间】:2021-11-28 07:56:45
【问题描述】:
为什么这行不通。有没有办法做到这一点? 我不想为指针创建单独的函数
#include <iostream>
using namespace std;
template<class T>
class temp
{
public:
T val;
temp(T value) : val(value) {}
~temp()
{
if(is_pointer<T>::value)
{
delete val;
}
}
};
int main()
{
string * n = new string("cat");
temp<string*>object(n);//ok
temp<string>object2("dog"); //compliation error: type 'class std::cxx11::basic_string' argument given to 'delete', expected pointer. --- (but there is if statement!!!!)
//i dont want delete in main
return 0;
}
要编译,我使用 g++ 6.3.0 有人可以帮忙吗?也许,我需要将声明与定义分开?
【问题讨论】:
-
请提供更多信息,如配置、编译器、C++ 版本、错误详情和实际问题。
-
从技术上讲,您的
temp类并不拥有指针或它指向的数据的所有权。所以它不应该尝试delete它。 -
永恒的基本规则是:
delete你用new创建的,delete[]你用new[]创建的。如果您将指针传递给temp,您仍然不能确定它是否可以是deleted 而不会导致未定义行为。想象一下,我将您的temp<int*>用于int i; temp<int*> tI(&i);... -
new string("cat")是代码异味,不在main中删除它只会让它变得更糟。你能解释一下目标是什么吗?为什么不temp<string>?或者如果你坚持动态分配temp< std::unique_ptr<std::string>>? -
使用 C++17
if constexpr (is_pointer<T>::value)将允许它编译(尽管它仍然会有其他评论者提到的问题)
标签: c++ pointers templates destructor dynamic-memory-allocation