【发布时间】:2016-01-05 08:25:09
【问题描述】:
我正在为一个类创建一个函数,并且参数被声明为 void* 但是在函数中我需要测试这个 void* 是 shared_ptr 还是 unique_ptr 有没有办法测试这种类型的情况?
这是我目前正在使用的;我的类是模板类型,不存储任何成员变量。它有一个默认构造函数,也可以通过传入shared_ptr<Type> 或unique_ptr<Type> 来构造它,它有多个allocate() 函数,它们执行相同类型的工作。
#ifndef ALLOCATOR_H
#define ALLOCATOR_H
#include <memory>
#include <iostream>
template<class Type>
class Allocator {
public:
Allocator(){}
Allocator( Type type, void* pPtr );
Allocator( std::shared_ptr<Type>& pType );
Allocator( std::unique_ptr<Type>& pType );
// ~Allocator(); // Default Okay
void allocate( std::shared_ptr<Type>& pType );
void allocate( std::unique_ptr<Type>& pType );
void allocate( Type type, void* pPtr );
private:
Allocator( const Allocator& c ); // Not Implemented
Allocator& operator=( const Allocator& c ); // Not Implemented
}; // Allocator
#include "Allocator.inl"
#endif // ALLOCATOR_H
我的*.cpp 文件只有#include "Allocator.h",因为所有实现都在我的*.inl 文件中。
我的两个构造函数:Allocator( std::shared_ptr<Type>& pType ); 和 Allocator( std::unique_ptr<Type>& pType ); 以及两个匹配的 allocate() 函数都可以正常工作。构造函数Allocator( Type type, void* pPtr ); 及其匹配函数是我遇到问题的地方。
构造函数本身很简单,因为它所做的只是调用匹配函数,将变量传递给它。
template<class Type>
Allocator<Type>::Allocator( Type type, void* pPtr ) {
allocate( type, eType, pPtr );
}
我在函数实现中苦苦挣扎。
template<class Type>
void Allocator<Type>::allocate( Type type, void* pData ) {
if ( pData == reinterpret_cast<void*>( std::shared_ptr<Type ) ) {
std::shared_ptr<Type> pShared;
pShared.reset( new Type( type ) );
pData = reinterpret_cast<void*>( pShared );
} else if ( pData == reinterpret_cast<void*>( std::unique_ptr<Type ) ) {
std::unique_ptr<Type> pUnique;
pUnique.reset( new Type( type ) );
pData = reinterpret_cast<void*>( pUnique );
} else {
std::cout << "Error invalid pointer type passed in << std::endl
<< "must be either a std::shared_ptr<Type> << std::endl
<< "or a std::unique_ptr<Type> << std::endl;
}
}
除了检查传入的void*是std::shared_ptr<Type>还是std::unique_ptr<Type>之外,我可能还有其他问题,我使用reinterpret_cast<void*>是转换智能指针的正确方法吗到一个空指针,如果不是,如何实现?
【问题讨论】:
-
奇怪的东西。有什么需要?
-
没有基本的需要,只是一个自我想要的练习来加强我的模板技能。我认为这将是一个不错的实用程序类型类,您可以在其中使用所需类型对其进行实例化,然后调用其成员函数来创建该类型的 shared_ptr 或 unique_ptr,或者使用其构造函数来做同样的事情。
-
你根本做不到,void 指针不携带任何类型信息,除非你可以使用合理的
reinterpret_cast来暗示它,在那里你完全知道如何解释内存void*指针指向的布局。 -
您的
void*是否指向共享/唯一指针?或者它是否指向共享/唯一 ptr 指向的内容?或者您是否真的试图将共享/唯一 ptr 的字节重新解释为void*?如果第三种可能性(正如您的其他代码所暗示的那样),那么我认为您注定要失败。在其他问题中,不能保证 void 指针的大小与共享/唯一指针的大小相同(我相信 shared_ptr 可能永远不会是相同的大小)。 -
当函数被调用或调用时,该方法不知道用户是要传入 shared_ptr 还是 unique_ptr。我在它的声明中使用了 void*,但是当使用该函数时,需要传入一个或另一个。
标签: c++ smart-pointers void-pointers reinterpret-cast