When would you use an array rather than a vector/string?

前端 未结 8 2048
醉梦人生
醉梦人生 2020-12-01 19:09

I\'m a beginner C++ programmer and so I\'ve learnt using arrays rather than vectors (this seems to be the general way to do things, then move on to vectors later on).

<
8条回答
  •  悲哀的现实
    2020-12-01 19:32

    I work on a shared library that needs access to structured data. This data is known at compile time, so it uses file-scoped constant arrays of POD (plain old data) structures to hold the data.

    This causes the compiler and linker to put most of the data in a read-only section, with two benefits:

    • It can be mapped into memory directory from disk without running any special initialization code.
    • It can be shared between processes.

    The only exception is that the compiler still generates initialization code to load floating point constants, so any structure containing floating point numbers ends up in a writable section. I suspect that this has something do with floating exceptions or floating point rounding modes, but I'm not sure how to verify either hypothesis.

    If I used vector and string objects for this, then the compiler would generate a lot more initialization code that would execute whenever my shared library is loaded. The constant data would be allocated on the heap, so it would not be shareable between processes.

    If I read the data in from a file on disk, I would have to deal with checking the format of the data, instead of having the C++ compiler do it for me. I also would have to manage the lifetime of the data in a codebase that has had this global data "baked into" it since the beginning.

提交回复
热议问题