How to get the address of the std::vector buffer start most elegantly?

后端 未结 11 2149
-上瘾入骨i
-上瘾入骨i 2020-12-03 18:12

I want to use std::vector for dynamically allocating memory. The scenario is:

int neededLength = computeLength(); // some logic here

// this will allocate t         


        
相关标签:
11条回答
  • 2020-12-03 18:35

    The reason it looks ugly is because you're at the borderline of nice and clean C++ style code and nice and clean C style code. The C++ code uses iterators, the C code uses pointers and sizes.

    You could create some glue to circumvent these problems:

    template< typename at_Container, typename at_Function >
    void for_container( at_Container& c, at_Function f ) {
        f( &c[0], c.size() );
    }
    

    and call it in the client code.

    void afunction( int* p, size_t n ) { 
       for( int* p = ap; p != ap+n; ++p ) {
         printf( "%d ", *p );
       }
    }
    
    void clientcode() {
       std::vector<int> ints(30,3);
       for_container( ints, afunction );
    }
    
    0 讨论(0)
  • 2020-12-03 18:37

    If you're using std::vector just for its RAII properties (so that it will free the memory for you), and you don't actually need it to resize or anything, you might be better off using a Boost scoped_array

    boost::scoped_array<TCHAR> buffer( new TCHAR[neededLength] );
    callFunction( buffer.get(), neededLength );
    

    scoped_array will call delete[] on the array when it goes out of scope.

    0 讨论(0)
  • 2020-12-03 18:40

    No.

    0 讨论(0)
  • 2020-12-03 18:41

    It's really odd that nobody know this!!! in C++11 you could use:

    buffer.data()
    

    it could get the address of the vector I have test it:

    vector<char>buffer;
    buffer.push_back('w');
    buffer.push_back('h');
    buffer.push_back('a');
    buffer.push_back('t');
    buffer.push_back('\0');
    char buf2[10];
    memcpy(buf2,buffer.data(),10);
    

    Specification here.

    0 讨论(0)
  • 2020-12-03 18:41

    Try &(buffer.front()), but it's not much prettier :)

    0 讨论(0)
提交回复
热议问题