If the caller and the function are consistent with the class’s memory layout (i.e. with the same compiler and settings), is it safe for a C-shaped function to return a class created from the class template?
Example:
#include <vector> #include <iostream> extern "C" std::vector<int> foo() { return {{1, 2, 3}}; } int main() { const auto v = foo(); for (const auto& i : v) std::cout << i << " "; std::cout << std::endl; }
The program compiles and runs with g ++ 4.9.2 and clang 3.5. g ++ does not raise any warnings, but causes problems:
test.cpp: 4: 29: warning: 'foo' has a C-linkage, but returns an incomplete type 'std :: vector', which may not be compatible with C [-Wreturn-type-c-link]
This error does not make sense to me, because std::vector<int> not an incomplete type. The fact that this code creates an instance of std::vector<int> demonstrates that std::vector<int> is a full type.
source share