Tải bản đầy đủ - 0 (trang)
Chapter 78.  Use vector (and string::c_str) to exchange data with non-C++ APIs

Chapter 78.  Use vector (and string::c_str) to exchange data with non-C++ APIs

Tải bản đầy đủ - 0trang

Summary

vectorisn'tlostintranslation:vectorandstring::c_strare

yourgatewaytocommunicatewithnon-C++APIs.Butdon't

assumeiteratorsarepointers;togettheaddressofthe

elementreferredtobyavector::iteratoriter,use

&*iter.



Discussion

vector(primarily)andstring::c_strandstring::data

(secondarily)arethebestwaytocommunicatedatawithnonC++APIsingeneral,andClibrariesinparticular.

vector'sstorageisalwayscontiguous,soaccessingtheaddress

ofitsfirstelementreturnsapointertoitscontents.Use

&*v.begin(),&v[0],or&v.front()togetapointertov'sfirst

element.Togetapointertoavector'sn-thelement,preferto

dothearithmeticfirstandtaketheaddresslater(e.g.,

&v.begin()[n]or&v[n])insteadoffetchingapointertofront

andthendoingpointerarithmetic(e.g.,(&v.front())[n]).

Thisisbecauseintheformercaseyouaregivingachecked

implementationacrackatverifyingthatyoudon'taccessan

elementoutsidev'sbounds(seeItem83).

Donotassumethatv.begin()returnsapointertothefirst

element,oringeneralthatvectoriteratorsarepointers.

AlthoughsomeSTLimplementationsdodefine

vector::iteratorsasbareT*pointers,iteratorscanbe,

andincreasinglyare,full-blowntypes(seeagainItem83).

Althoughmostimplementationsusecontiguousmemoryfor

string,that'snotguaranteed,sonevertaketheaddressofa

characterinastringandassumeitpointstocontiguous

memory.Thegoodnewsisthatstring::c_stralwaysreturns

anull-terminatedC-stylestring.(string::dataalsoreturnsa

pointertocontiguousmemory,exceptthatit'snotguaranteed

tobezero-terminated.)

Whenyoupasspointersintoavectorv'sdata,Ccodecan

bothreadfromandwritetov'selementsbutmuststaywithin

size'sbounds.Awell-designedCAPItakesamaximum

numberofobjects(uptov.size())orapast-the-endpointer



(&*v.begin()+v.size()).

IfyouhaveacontainerofTobjectsotherthanvectoror

stringandwanttopassitscontentsto(orpopulateitfrom)a

non-C++APIthatexpectsapointertoanarrayofTobjects,

copythecontainer'scontentsto(orfrom)avectorthatcan

directlycommunicatewiththenon-C++API.



References

[Josuttis99]Đ6.2.3,Đ11.2.4[Meyers01]Đ16[Musser01]ĐB

[Stroustrup00]Đ16.3.1



79.Storeonlyvaluesandsmartpointers

incontainers

Summary

Discussion

Examples

References



Summary

Storeobjectsofvalueincontainers:Containersassumethey

containvalue-liketypes,includingvaluetypes(helddirectly),

smartpointers,anditerators.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 78.  Use vector (and string::c_str) to exchange data with non-C++ APIs

Tải bản đầy đủ ngay(0 tr)

×