警告级别为 3 的 int std::vector push_back 处的编译器警告
Compiler warning at std::vector push_back of an int with warning level 3
我使用的是 intel c++ 编译器 icc 版本 18.0.3。
如果我用 -w3
编译 following code
#include <vector>
int main() {
std::vector<int> vec;
vec.push_back(2);
return 0;
}
test_w3.cpp(6): remark #383: value copied to temporary, reference to
temporary used
vec.push_back(2);
Replacing 带有 const 变量的 2
as
#include <vector>
int main() {
std::vector<int> vec;
const int a = 2;
vec.push_back(a);
return 0;
}
不发出警告。
这个警告是什么意思?可以安全地忽略它吗(尽管无警告代码是可取的)?
英特尔有一个网站专门针对您的问题 here。它是从 2008 年开始的,但似乎适用于您的问题。 警告存在,因为这种编程风格可能会导致隐藏临时对象,在某些情况下可以忽略。
他们为这个例子声明:
void foo(const int &var)
{
}
void foobar()
{
std::vector<std::string> numlist
// 383 remark here: a tempory object with "123" is created
numlist.push_back("123");
foo(10); // gives 383
}
以下:
Resolution:
- Provide a proper object for initializing the reference.
- Can safely ignore this warning for pushback function of vector. The vector copies the argument into its own storage; it never stores the original argument. Therefore, using a temporary is perfectly safe.
因此您可以忽略警告,即使这与一般规则相矛盾永远不要忽略警告。
在我看来英特尔选择了一个糟糕的方式,因为误诊导致的警告阻碍了发展。
我使用的是 intel c++ 编译器 icc 版本 18.0.3。
如果我用 -w3
#include <vector>
int main() {
std::vector<int> vec;
vec.push_back(2);
return 0;
}
test_w3.cpp(6): remark #383: value copied to temporary, reference to temporary used vec.push_back(2);
Replacing 带有 const 变量的 2
as
#include <vector>
int main() {
std::vector<int> vec;
const int a = 2;
vec.push_back(a);
return 0;
}
不发出警告。
这个警告是什么意思?可以安全地忽略它吗(尽管无警告代码是可取的)?
英特尔有一个网站专门针对您的问题 here。它是从 2008 年开始的,但似乎适用于您的问题。 警告存在,因为这种编程风格可能会导致隐藏临时对象,在某些情况下可以忽略。
他们为这个例子声明:
void foo(const int &var)
{
}
void foobar()
{
std::vector<std::string> numlist
// 383 remark here: a tempory object with "123" is created
numlist.push_back("123");
foo(10); // gives 383
}
以下:
Resolution:
- Provide a proper object for initializing the reference.
- Can safely ignore this warning for pushback function of vector. The vector copies the argument into its own storage; it never stores the original argument. Therefore, using a temporary is perfectly safe.
因此您可以忽略警告,即使这与一般规则相矛盾永远不要忽略警告。
在我看来英特尔选择了一个糟糕的方式,因为误诊导致的警告阻碍了发展。