Compiler warning at std::vector push_back of an int with warning level 3

Viewed 354

I am using the intel c++ compiler icc version 18.0.3.

If I compile the following code with -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 the 2 with a const variable as

#include <vector>
int main() {
    std::vector<int> vec;
    const int a = 2;
    vec.push_back(a);
    return 0;
}

does not give a warning.

What does this warning mean? Can it safely be ignored (although warning free code is desirable)?

1 Answers

Intel has a site for exactly this issue with exactly your problem here. It is from 2008, but seems to be applicable to your problem. The warning exists, as this programming style may lead to hidden temporary objects and can be ignored in some cases.

They state for this example:

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

}

The following:

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.

So you may ignore the warning, even though this contradicts the general rule never ignore warnings.

In my opinion Intel has chosen a bad way, as warnings which result from misdiagnosis hinder development.

Related