简体   繁体   中英

How to read data block from a file using smart pointers?

When using raw pointers I was able to do that:

std::vector< Vector3* > vertices;
Vector3* v = new Vector3[amount];
fread(v, sizeof(Vector3), amount, file);
for ( int i = 0; i < amount; ++i )
    vertices.push_back( &v[i] );

now, how to do the same with smart pointers? I was tried something like this:

std::vector< std::unique_ptr< Vector3 > > vertices;
std::unique_ptr< Vector3 >* v = new std::unique_ptr< Vector3 >[amount];
fread(v, sizeof(Vector3), amount, file);
for ( int i = 0; i < amount; ++i )
    vertices.push_back( std::move( v[i] ) );
delete [] v;

does it have any sense? It compiles, and it works, but I'm afraid the last instruction ( delete [] v; ) is this correct?

Take it easy

std::vector<Vector3> vertices(amount);
assert(!vertices.empty());
fread(&vertices[0], sizeof(Vector3), amount, file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM