Search code examples
c++visual-studiog++forward-declarationpvs-studio

Does PVS-Studio know about forward declaration necessity?


There is a problem when different compilers behave differently. Pity, PVS doesn't tell me about the following dangerous situation.

I have some overloaded functions but I forget to write a forward declaration. So Visual Studio compiles a one program and other compilers another one.

My functions:

// For simple types (i.e. int, bool, char) and plain old data
template <typename T>
void serialize(T pod, std::ostream& out) {
    std::cout << "pod\n";
    out.write(reinterpret_cast<const char*>(&pod), sizeof(T));
}

void serialize(const std::string& str, std::ostream& out) {
    std::cout << "string\n";
    serialize(str.size(), out);

    out.write(str.data(), str.size());
}

template <typename T>
void serialize(const std::vector<T>& data, std::ostream& out) {
    std::cout << "vector\n";
    serialize(data.size(), out);

    for (const T& elem : data) {
        serialize(elem, out); // <== runs POD serialization for map :(
    }
}

template <typename T1, typename T2>
void serialize(const std::map<T1, T2>& data, std::ostream& out) {
    std::cout << "map\n";
    serialize(data.size(), out);

    for (const auto& p : data) {
        serialize(p.first, out);
        serialize(p.second, out);
    }
}

I test this with the code:

std::vector<std::map<int, int>> v;
v.emplace_back();
v[0][1] = 2;

std::stringstream ss;

serialize(v, ss);

Testing in VS was OK (both debug and release versions):

vector
pod [size of vector]
map
pod [size of map]
pod [key = 1]
pod [value = 2]

But suddenly my colleague tells me that nothing is working at all.

I've tested on different compilers (thanks to the Ideone site). All behave the wrong way (gcc 4.3.2, 6.3; clang 4.0):

vector
pod [size of vector]
pod [map]

Of course, after placing forward declarations before of all functions, everything became right in all compilers.

I ask to implement a warning about a forward declaration.


Solution

  • Yes, there is such an underworking in PVS-Studio. We'll do our best to fix it over time.