0

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.

SerVB
  • 129
  • 17
  • Hmm... "It is simply a description of underworking, rather than a question. Bug reports and feature requests are not on-topic here on Stack Overflow." Is it the same case? – SerVB Mar 09 '18 at 13:14
  • How would the compiler know that you meant to forward declare those functions? At the point you indicated there's a perfectly good overload (an instantiation of your first template) right there. You should constrain your first function to only take PODs if it's meant only for PODs, then the compiler will not find an overload that fits and will give an error. – Pezo Mar 09 '18 at 13:32
  • Thank you, we will try to improve the analysis of PVS-Studio. – Svyatoslav Razmyslov Mar 20 '18 at 09:51

1 Answers1

0

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