析构函数指针和非指针



为什么不能工作?有什么办法可以做到吗?我不想为指针

创建一个单独的函数
#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编译有人能帮忙吗?也许,我需要把声明和定义分开?

您的问题是,if的分支必须始终在语法上有效,即使它从未被采用。

可以if constexpr来做,这是一个"编译时间if">

~temp()
{
if constexpr(is_pointer<T>::value)
{
delete val;
}
}

但这并不安全。

你怎么知道传递给temp<T*>的指针是由new创建的,而不是由new[]malloc创建的,或者是通过获取一个没有动态分配的对象的地址创建的?

与其假定指针应该被删除,不如避免知道要删除哪些指针

#include <string>
#include <memory>
template<class T>
class temp
{
public:
T val;
temp(T value) : val(value) {}
// n.b. no need to define destructor
};
int main()
{
std::string str("cat");
temp<std::string*> object(&str);//ok
temp<std::string> object2("dog"); // also ok
std::unique_ptr<std::string> str2 = std::make_unique<std::string>("mouse");
temp<std::string *> object3(str2.get()); // ok so long as str2 outlives object3
std::shared_ptr<std::string> str3 = std::make_shared<std::string>("rabbit");
temp<std::shared_ptr<std::string>> object4(str3); // also ok
return 0;
}

最新更新