我正在尝试通过引用成员函数作为参数并将其分配给新对象,iDE给我一个警告说,我应该避免使用未命名的对象带有定制的建筑和破坏。因此,我在询问这样做的选择,或者要了解警告是什么意思。
我正在使用C 17,该程序正常运行,一切都很好,但是我只是不知道要摆脱警告的替代方法。
实际警告消息:Warning C26444 Avoid unnamed objects with custom construction and destruction (es.84). Project2 c:xxreposproject2project2big_int.cpp 304
void big_int::copyInto(big_int& b) {
b = big_int{this->data}; // this->data is string
}
假设big_int
类的构造函数需要string
,这线给了我上述警告。
P.S。:我知道这正是复制构造函数本身的工作,但是我只是举一个例子来阐述我的问题。
nitpick:这没有调用构造函数。直接这样做是不可能的。语法看起来像它,但是没有语法要做。
您真正在做的是创建类型big_int
的临时,然后将其分配给b
。
我想不出什么错。奇怪的警告。
您可以通过将新对象提升到命名变量,然后将其纳入 move 分配它来解决它,但是该代码完全是冗长的,而IMO完全不需要。(并且我 think 它禁止保证省略?不确定这与这个特定的例子相关,但是嘿。(
我只是禁用警告。
避免未命名的对象[..]
所以命名:
void big_int::copyInto(big_int& b) {
auto temp = big_int{this->data}; // this->data is string
b = std::move(temp);
}
或明确禁用警告
void big_int::copyInto(big_int& b) {
#pragma warning (push)
#pragma warning (disable : 26444) // Avoid unnamed objects with custom construction and destruction
b = big_int{this->data}; // this->data is string
#pragma warning (pop)
}