我如何从常规指针中区分数组指针
how do I tell an array pointer from a regular pointer
我正在写一个像std::shared_ptr这样的智能指针,因为我的编译器不支持c++17及以后的版本,我想支持像这样的数组指针:
myptr<char []>(new char[10]);
好吧,实际上一切顺利,直到我遇到与旧版本相同的问题 std::shared_ptr 得到:
myptr<char []>(new char);
是的,它无法判断它是常规指针还是数组指针,因为我的删除器有点像:
deleter = [](T *p) {delete[] p;}
这意味着它遇到了与旧版本 std::shared_ptr 相同的问题。
我的数组指针偏特化如下:
template <typename T, typename DeleterType>
class myptr<T[], DeleterType> { // DeleterType has a default param in main specialization
// as std::function<void(T*)>
private:
my_ptr_cnt<T, DeleterType> *p; // this is the actual pointer and count maintain class
public:
// constructor
/// \bug here:
my_ptr(T *p, DeleterType deleter=[](T *p) {delete []p;}) :
p(new my_ptr_cnt<T, DeleterType>(p, deleter)) { }
}
你不能。这是原始数组不好的众多原因之一。
你可以做的是禁止从原始指针构造,并依赖于 make_shared
-like 构造。
我正在写一个像std::shared_ptr这样的智能指针,因为我的编译器不支持c++17及以后的版本,我想支持像这样的数组指针:
myptr<char []>(new char[10]);
好吧,实际上一切顺利,直到我遇到与旧版本相同的问题 std::shared_ptr 得到:
myptr<char []>(new char);
是的,它无法判断它是常规指针还是数组指针,因为我的删除器有点像:
deleter = [](T *p) {delete[] p;}
这意味着它遇到了与旧版本 std::shared_ptr 相同的问题。
我的数组指针偏特化如下:
template <typename T, typename DeleterType>
class myptr<T[], DeleterType> { // DeleterType has a default param in main specialization
// as std::function<void(T*)>
private:
my_ptr_cnt<T, DeleterType> *p; // this is the actual pointer and count maintain class
public:
// constructor
/// \bug here:
my_ptr(T *p, DeleterType deleter=[](T *p) {delete []p;}) :
p(new my_ptr_cnt<T, DeleterType>(p, deleter)) { }
}
你不能。这是原始数组不好的众多原因之一。
你可以做的是禁止从原始指针构造,并依赖于 make_shared
-like 构造。