2

I am developing a library which have C interface for compatibility purpose

void interface(double* context, size_t num_elements);

while context points to a raw memory storing num_elements doubles. In the remaining part of the code, is there any strategies to construct a std::valarray which temporarily manage the context without freeing it after the library call is over?

xis
  • 24,330
  • 9
  • 43
  • 59

1 Answers1

0

Couldn't you create a simple container to suit your needs? Here is a small example I didn't test:

template <class T>
class custom_valarray
{
public:

    // Ctor/dtor
    custom_valarray() { clear(); }
    ~custom_valarray() { clear(); }
    custom_valarray( T *ptr, const unsigned &s ) { set(ptr,s); }

    // Clear container
    void clear() { data = nullptr; size = 0; }

    // Set data
    void set( T *ptr, const unsigned &s ) { data = ptr; size = s; }

    // Test if container is set
    operator bool() const { return data; }
    bool empty() const { return data; }

    // Accessors
    T* data() { return data; }
    T& operator[] ( const unsigned &i ) 
    { 
        static T garbage;
        return i < size ? data[i] : garbage; 
    }

    // Iterators
    T* begin() { return data; }
    T* end() { return data+size; }

private:

    T *data;
    unsigned size;
};
Jonathan H
  • 7,591
  • 5
  • 47
  • 80
  • Well, of course it is ok but I know valarray has special optimization in C++ in some cases. – xis Feb 26 '13 at 20:17
  • What kind of operation do you intend to do with your valarray that requires to be optimized? Although there is no magic, you can checkout a standard implementation there if needed: http://gcc.gnu.org/onlinedocs/gcc-4.6.3/libstdc++/api/a01109_source.html – Jonathan H Feb 26 '13 at 21:13