interface with std::vectors

Started by
3 comments, last by Fruny 17 years, 10 months ago
I'm wondering, are std::vectors acceptable as interface for a library or something similar? Because, in the case of the png decoder I made, you have to give as parameters: an std::vector<unsigned char> containing the contents of the file, an empty std::vector<unsigned char>& that will be filled with the pixels of the image, and an empty std::vector<int>& that will be filled with information like the width and height of the image. So basically, when using this little library you have to make std::vectors and pass them to the function of the library. I don't think I've ever seen a library or API that used std::vectors, because most of them are for C too instead of only C++. My thing is only for C++ though, I find std::vectors much more conveniant, you don't have to think about memory allocation, they're standard C++, and don't decrease performance if you compile with optimization. So do you think it's annoying, or bad, to make it this way? Would it be better if you instead have to give normal C-style buffers, or those C++ things that will be allocated with "new[]" and "delete[]" as parameters?
Advertisement
When you use a templated class, such as std::vector, in a library distributed as object code, it will only be compatible with code compiled with the same compiler, the same compile settings and same template implementation. This is generally a bad thing for distributing a library. However, if you're library is a source code library, then it's less of a problem.
It's a source code library.

But wow that's bad about those templates... And they call that standard C++!! :(
Quote:Original post by Lode
But wow that's bad about those templates... And they call that standard C++!! :(

But the C++ code is standard. The binary files generated by the compiler, however, is not.
Quote:Original post by Lode
My thing is only for C++ though, I find std::vectors much more conveniant, you don't have to think about memory allocation, they're standard C++, and don't decrease performance if you compile with optimization.


The interface is standard. The implementation is not. If I pass a vector that has an incompatible implementation to your library, Bad Things will happen. If you want to use a vector as part of the library's interface, you will have to use a C++ header file with an inline interface that acts as a front-end to a C interface.

foo.h
int foo_impl(int* buf, int size); // in the libraryinline int foo(std::vector<int>& vec){   return foo_impl(&vec.front(), vec.size());}
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement