Is it safe to return a class template from a function using C-style?

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.

+5
source share
1 answer

I would use returning shared_ptr objects via the C interface. The nice thing is that a proper deleter will be called on the object when it is no longer available.

From: http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

The deleter associated with r is stored for subsequent deletion of the managed entity.

Also see Scott Meyers post on this topic:

Understanding how removers work in Boosts shared_ptr http://www.artima.com/cppsource/top_cpp_aha_moments.html

It is even better to discuss the Cross DLL problem in the accepted answer here: Is it possible to use boost :: shared ptr in the DLL interface?

Since the return type is not part of the function, the function name. You should still use the C style if you want.

0
source

Source: https://habr.com/ru/post/1213394/


All Articles