当我编译以下测试代码时,我收到此警告:
test.cu(49): warning: missing return statement at end of non-void function "AllocateSize<T,D>(size_t) noexcept [with T=int, D=Device::GPU]"
detected during instantiation of "Pointer<T, D> AllocateSize<T,D>(size_t) noexcept [with T=int, D=Device::GPU]"
(61): here
我应该担心吗,这是预期的吗?我该怎么做才能让它消失?这看起来很奇怪,因为 cuda 确实支持 C++17。提前致谢!编译:
nvcc -std=c++17 test.cu -o test
测试代码( test.cu
):enum class Device { CPU, GPU }; // Device
template <typename T, Device D>
class Pointer {
private:
T* m_raw = nullptr;
public:
__host__ __device__ inline Pointer(T* const p) noexcept { this->SetPointer(p); }
__host__ __device__ inline void SetPointer(const Pointer<T, D>& o) noexcept { this->m_raw = o.m_raw; }
template <typename U>
__host__ __device__ inline Pointer<U, D> AsPointerTo() const noexcept {
return Pointer<U, D>(reinterpret_cast<U*>(this->m_raw));
}
__host__ __device__ inline operator T*& () noexcept { return this->m_raw; }
}; // Pointer<T, D>
template <typename T>
using CPU_Ptr = Pointer<T, Device::CPU>;
template <typename T>
using GPU_Ptr = Pointer<T, Device::GPU>;
template <typename T, Device D>
__host__ inline Pointer<T, D> AllocateSize(const size_t size) noexcept {
if constexpr (D == Device::CPU) {
return CPU_Ptr<T>(reinterpret_cast<T*>(std::malloc(size)));
} else {
T* p;
cudaMalloc(reinterpret_cast<void**>(&p), size);
return GPU_Ptr<T>(p);
}
}
template <typename T, Device D>
__host__ inline void Free(const Pointer<T, D>& p) noexcept {
if constexpr (D == Device::CPU) {
std::free(p);
} else {
cudaFree(p.template AsPointerTo<void>());
}
}
int main() { Free(AllocateSize<int, Device::GPU>(1024)); }
最佳答案
我们的编译器团队研究了这个问题。该警告是虚假警告。我们希望在 future 的 CUDA 版本中解决这个问题。我将无法回答有关何时可能出现的问题。代码正在正确生成。
如果您希望消除警告,一种可能的方法是在相关函数的末尾添加额外的 return 语句。在这种情况下,这应该不起作用,因为它无法访问:
template <typename T, Device D>
__host__ inline Pointer<T, D> AllocateSize(const size_t size) noexcept {
if constexpr (D == Device::CPU) {
return CPU_Ptr<T>(reinterpret_cast<T*>(std::malloc(size)));
} else {
T* p;
cudaMalloc(reinterpret_cast<void**>(&p), size);
return GPU_Ptr<T>(p);
}
return Pointer<T, D>(NULL);
}
(3028897)
关于c++ - CUDA: "missing return statement at end of non-void function"in constexpr if 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64523302/