【发布时间】:2015-07-17 15:59:15
【问题描述】:
我使用 Embacadero C++Builder。我有以下问题:
我曾经遵循指南,并在编译期间尽量不出现警告(通过修复代码,而不是通过禁用警告)。
我也使用std::unique_ptr<>。
但事实证明 std::unique_ptr 的实现有一个错误(至少它会在发布模式下触发 32 位平台上的警告,当我查看实现时,似乎该实现不是百分百正确)。
细节(示例代码)。我尝试在发布配置中使用 32 位编译器构建以下代码
#include <memory>
using namespace std;
int main()
{
unique_ptr<int> myUniqueInt;
int * myInt = new int(5);
myUniqueInt = unique_ptr<int>(move(myInt));
return 0;
}
然后我收到警告:[bcc32 Warning] memory(806): W8070 Function should return a value
现在,如果我查看警告的来源,我会看到以下内容(文件“memory”,第 798 行,来自标准库):
_Myt& operator=(_Myt&& _Right)
{ // assign by moving _Right
if (this != &_Right)
{ // different, do the move
reset(_Right.release());
this->get_deleter() = _STD move(_Right.get_deleter());
return (*this);
}
}
我们可以看到,确实如果this == &_Right,那么函数没有返回任何值,所以警告是正确的。
我的问题如下:
- 为什么在 Debug 配置中未触发警告 - 它仅在发布时触发?
- 如何在不放弃全局“将警告视为错误”且不全局禁用此警告的情况下克服此问题。
注意事项:
- 警告仅在发布配置中出现。
- XE6 和 XE8 版本的 C++Builder 上出现警告
- 64 位编译器不存在警告(这是预期的,因为编译器不同)。
提前致谢。
【问题讨论】:
-
请注意这里不需要
std::move。unique_ptr<int>(myInt);会很好,unique_ptr<int> myUniqueInt(new int(5))更好,unique_ptr<int> myUniqueInt = make_unique<int>(5);如果你有 make_unique 会更好。 -
谢谢。你当然是对的。我最初的例子是两个
unique_ptr对象,它是必需的。我在简化示例时忘记删除它。我知道make_unique,但我没有(如果我没记错的话,它只在 C++14 中可用,即只在最新版本的编译器中可用)。 -
请参阅 this answer 以了解您可以放入项目中的
make_unique()的实现。真的很简单。
标签: c++ stl c++builder compiler-warnings