Перейти к содержимому

Any of c что это

  • автор:

What is a «span» and when should I use one?

Recently I’ve gotten suggestions to use span ‘s in my code, or have seen some answers here on the site which use span ‘s — supposedly some kind of container. But — I can’t find anything like that in the C++17 standard library. So what is this mysterious span , and why (or when) is it a good idea to use it if it’s non-standard?

asked Aug 16, 2017 at 22:15
120k 59 59 gold badges 346 346 silver badges 704 704 bronze badges

@jww: span’s are quite usable with C++11. as gsl::span rather than std::span . See also my answer below.

Jan 24, 2018 at 6:39
Also documented on cppreference.com: en.cppreference.com/w/cpp/container/span
Mar 24, 2020 at 19:18
@KeithThompson: Not in 2017 it wasn’t.
Mar 24, 2020 at 21:02

@jww All compilers support std::span<> now in C++20 mode. And span is available from many 3rd party libs. You were right — it was years: 2 years to be precise.

Jun 20, 2020 at 7:43

4 Answers 4

What is it?

  • A very lightweight abstraction of a contiguous sequence of values of type T somewhere in memory.
  • Basically a struct < T * ptr; std::size_t length; >with a bunch of convenience methods.
  • A non-owning type (i.e. a «reference-type» rather than a «value type»): It never allocates nor deallocates anything and does not keep smart pointers alive.

It was formerly known as an array_view and even earlier as array_ref .

When should I use it?

First, when not to use spans:

  • Don’t use a span in code that could just take any pair of start & end iterators (like std::sort , std::find_if , std::copy and other templated functions from ), and also not in code that takes an arbitrary range (see The C++20 ranges library for information about those). A span has stricter requirements than a pair of iterators or a range: element contiguity and presence of the elements in memory.
  • Don’t use a span if you have a standard library container (or a Boost container etc.) which you know is the right fit for your code. spans are not intended to supplant existing containers.

Now for when to actually use a span:

Use span (respectively, span ) instead of a free-standing T* (respectively const T* ) when the allocated length or size also matter. So, replace functions like:

void read_into(int* buffer, size_t buffer_size); 
void read_into(span buffer); 

Why should I use it? Why is it a good thing?

Oh, spans are awesome! Using a span.

  • means that you can work with that pointer+length / start+end pointer combination like you would with a fancy, pimped-out standard library container, e.g.:
    • for (auto& x : my_span) < /* do stuff */ >
    • std::find_if(my_span.cbegin(), my_span.cend(), some_predicate);
    • std::ranges::find_if(my_span, some_predicate); (in C++20)

    . but with absolutely none of the overhead most container classes incur.

    int buffer[BUFFER_SIZE]; read_into(buffer, BUFFER_SIZE); 

    becomes this:

    int buffer[BUFFER_SIZE]; read_into(buffer); 

    There’s even more motivation for using span s, which you could find in the C++ core guidelines — but you catch the drift.

    But is it in the standard library?

    edit: Yes, std::span was added to C++ with the C++20 version of the language!

    Why only in C++20? Well, While the idea is not new — its current form was conceived in conjunction with the C++ core guidelines project, which only started taking shape in 2015. So it took a while.

    So how do I use it if I’m writing C++17 or earlier?

    It’s part of the Core Guidelines’s Support Library (GSL). Implementations:

    • Microsoft / Neil Macintosh’s GSL contains a standalone implementation: gsl/span
    • GSL-Lite is a single-header implementation of the whole GSL (it’s not that big, don’t worry), including span .

    The GSL implementation does generally assume a platform that implements C++14 support [12]. These alternative single-header implementations do not depend on GSL facilities:

    • martinmoene/span-lite requires C++98 or later
    • tcbrindle/span requires C++11 or later

    Note that these different span implementations have some differences in what methods/support functions they come with; and they may also differ somewhat from the version adopted into the standard library in C++20.

    Further reading: You can find all the details and design considerations in the final official proposal before C++17, P0122R7: span: bounds-safe views for sequences of objects by Neal Macintosh and Stephan J. Lavavej. It’s a bit long though. Also, in C++20, the span comparison semantics changed (following this short paper by Tony van Eerd).

    answered Aug 16, 2017 at 22:15
    120k 59 59 gold badges 346 346 silver badges 704 704 bronze badges

    It would make more sense to standardize a general range (supporting iterator+sentinel and iterator+length, maybe even iterator+sentinel+length) and make span a simple typedef. Because, you know, that’s more generic.

    Aug 17, 2017 at 12:47

    @Deduplicator: Ranges are coming to C++, but the current proposal (by Eric Niebler) requires support for Concepts. So not before C++20.

    Aug 17, 2017 at 12:52

    @HảiPhạmLê: Arrays don’t immediately decay into pointers. try doing std::cout
    Aug 23, 2017 at 7:59
    @Jim std::array is a container, it owns the values. span is non-owning
    Dec 4, 2018 at 14:18

    @Jim: std::array is a completely different beast. Its length is fixed at compile-time and it’s a value-type rather than a reference-type, as Caleth explained.

    Dec 4, 2018 at 14:56

    template struct span < T * ptr_to_array; // pointer to a contiguous C-style array of data // (which memory is NOT allocated nor deallocated // nor in any way managed by the span) std::size_t length; // number of elements of type `T` in the array // Plus a bunch of constructors and convenience accessor methods here >

    It is a light-weight wrapper around a C-style array, preferred by C++ developers whenever they are using C libraries and want to wrap them with a C++-style data container for «type safety» and «C++-ishness» and «feelgoodery». 🙂

    Note: I call the struct container defined above, known as a span, a «light-weight wrapper around a C-style array» because it points to a contiguous piece of memory, such as a C-style array, and wraps it with accessor methods and the array’s size. This is what I mean by «light-weight wrapper»: it is a wrapper around a pointer and a length variable, plus functions.

    Unlike a std::vector<> and other C++ standard containers, however, which may also just have fixed class sizes and contain pointers which point to their storage memory, a span does not own the memory it points to, and will never delete it nor resize it nor allocate new memory automatically. Again, a container like a vector owns the memory it points to, and will manage (allocate, reallocate, etc.) it, but a span does not own the memory it points to, and therefore will not manage it.

    Going further:

    @einpoklum does a pretty good job of introducing what a span is in his answer here. However, even after reading his answer, it is easy for someone new to spans to still have a sequence of stream-of-thought questions which aren’t fully answered, such as the following:

    1. How is a span different from a C array? Why not just use one of those? It seems like it’s just one of those with the size known as well.
    2. Wait, that sounds like a std::array , how is a span different from that?
    3. Oh, that reminds me, isn’t a std::vector like a std::array too?
    4. I’m so confused. 🙁 What’s a span ?

    So, here’s some additional clarity on that:

    DIRECT QUOTE OF HIS ANSWER—WITH MY ADDITIONS and parenthetical comments IN BOLD and my emphasis in italics:

    What is it?

    • A very lightweight abstraction of a contiguous sequence of values of type T somewhere in memory.
    • Basically a single struct < T * ptr; std::size_t length; >with a bunch of convenience methods. (Notice this is distinctly different from std::array<> because a span enables convenience accessor methods, comparable to std::array , via a pointer to type T and length (number of elements) of type T , whereas std::array is an actual container which holds one or more values of type T .)
    • A non-owning type (i.e. a «reference-type» rather than a «value type»): It never allocates nor deallocates anything and does not keep smart pointers alive.

    It was formerly known as an array_view and even earlier as array_ref .

    Those bold parts are critical to one’s understanding, so don’t miss them or misread them! A span is NOT a C-array of structs, nor is it a struct of a C-array of type T plus the length of the array (this would be essentially what the std::array container is), NOR is it a C-array of structs of pointers to type T plus the length, but rather it is a single struct containing one single pointer to type T , and the length, which is the number of elements (of type T ) in the contiguous memory block that the pointer to type T points to! In this way, the only overhead you’ve added by using a span are the variables to store the pointer and length, and any convenience accessor functions you use which the span provides.

    This is UNLIKE a std::array<> because the std::array<> actually allocates memory for the entire contiguous block, and it is UNLIKE std::vector<> because a std::vector is basically just a std::array that also does dynamic growing (usually doubling in size) each time it fills up and you try to add something else to it. A std::array is fixed in size, and a span doesn’t even manage the memory of the block it points to, it just points to the block of memory, knows how long the block of memory is, knows what data type is in a C-array in the memory, and provides convenience accessor functions to work with the elements in that contiguous memory.

    It is part of the C++ standard:

    std::span is part of the C++ standard as of C++20. You can read its documentation here: https://en.cppreference.com/w/cpp/container/span. To see how to use Google’s absl::Span(array, length) in C++11 or later today, see below.

    Summary Descriptions, and Key References:

    1. std::span ( Extent = «the number of elements in the sequence, or std::dynamic_extent if dynamic». A span just points to memory and makes it easy to access, but does NOT manage it!):
    2. https://en.cppreference.com/w/cpp/container/span
    3. std::array (notice it has a fixed size N !):
    4. https://en.cppreference.com/w/cpp/container/array
    5. http://www.cplusplus.com/reference/array/array/
    6. std::vector (automatically dynamically grows in size as necessary):
    7. https://en.cppreference.com/w/cpp/container/vector
    8. http://www.cplusplus.com/reference/vector/vector/

    How Can I Use span in C++11 or later today?

    Google has open-sourced their internal C++11 libraries in the form of their «Abseil» library. This library is intended to provide C++14 to C++20 and beyond features which work in C++11 and later, so that you can use tomorrow’s features, today. They say:

    Compatibility with the C++ Standard

    Google has developed many abstractions that either match or closely match features incorporated into C++14, C++17, and beyond. Using the Abseil versions of these abstractions allows you to access these features now, even if your code is not yet ready for life in a post C++11 world.

    Here are some key resources and links:

    1. Main site: https://abseil.io/
    2. https://abseil.io/docs/cpp/
    3. GitHub repository: https://github.com/abseil/abseil-cpp
    4. span.h header, and absl::Span(array, length) template class: https://github.com/abseil/abseil-cpp/blob/master/absl/types/span.h#L153

    Other references:

    1. Struct with template variables in C++
    2. Wikipedia: C++ classes
    3. default visibility of C++ class/struct members

    Related:

    1. [another one of my answers on templates and spans] How to make span of spans

    Перевод «of C» на русский

    Denote by fk and gk the number of k-gonal faces of the embedding that are inside and outside of C, respectively.

    Обозначим через fk и gk число k-угольных граней вложения, которые находятся внутри и вне C соответственно.

    Fourth, the ratio of C to C in the atmosphere is not constant.
    Кроме того, соотношение 14C/ 12C в атмосфере не постоянно.
    Thanks to the popularity of C++, the according CPP files are very well known as well.
    Благодаря популярности С ++ файлы СРР также очень хорошо известны.
    Because the Government of C won’t let us.
    «И мы с правительства не слезем.
    Turbo Vision: A set of C++ classes to create professional applications in DOS.
    Turbo Vision — набор классов C++ для создания профессиональных приложений в DOS.

    In the compositions of Ludwig van Beethoven, the key of C minor has been regarded by some as significant.

    В произведениях Людвига ван Бетховена тональность до минор расценивается специалистами как особо важная.

    Unlike Objective-C, Swift is a statically typed language that is not a strict extension of C.

    В отличие от Objective-C, Swift — статически типизированный язык, который не является строгим расширением C.

    French Utopian socialist and follower of C. Fourier.
    Французский социалист-утопист, последователь Ш. Фурье.
    Most of C Company moved all the way to the 25th Division positions south of the Naktong.
    Большая часть роты С прошло весь путь до позиций 25-й дивизии к югу от реки Нактонган.
    A Microsoft version of C++ with added Java-like functions.
    Microsoft версии C + + с добавлением Java-подобных функций.
    Accordingly, the map Δ is called the comultiplication (or coproduct) of C and ε is the counit of C.

    Соответственно, отображение Δ называется коумножением (или копроизведением) в C, а ε является коединицей C.

    Возможно неприемлемое содержание

    Примеры предназначены только для помощи в переводе искомых слов и выражений в различных контекстах. Мы не выбираем и не утверждаем примеры, и они могут содержать неприемлемые слова или идеи. Пожалуйста, сообщайте нам о примерах, которые, на Ваш взгляд, необходимо исправить или удалить. Грубые или разговорные переводы обычно отмечены красным или оранжевым цветом.

    Treatment — Hepatitis C

    If the infection is diagnosed in the early stages, known as acute hepatitis, treatment may not need to begin straight away.

    Instead, you may have another blood test after a few months to see if your body fights off the virus.

    If the infection continues for several months, known as chronic hepatitis, treatment will usually be recommended.

    Your treatment plan

    Treatment for chronic hepatitis C (those infected for 6 months or more) involves:

    • tablets to fight the virus
    • a test to see if your liver is damaged
    • lifestyle changes to prevent further damage

    There are 6 main strains of the virus. In the UK, the most common strains are genotype 1 and genotype 3. You can be infected with more than 1 strain.

    You’ll be offered the medicine most appropriate for your type of hepatitis C.

    During treatment, you should have blood tests to check that your medicine is working.

    If it’s not, you may be advised to try another medicine. This will only affect a small number of people.

    Your doctor will also assess your liver for damage (scarring), either with a blood test or a scan called a fibroscan.

    At the end of your treatment, you’ll have a blood test to see if the virus has been cleared and a second blood test 12 or 24 weeks after treatment has stopped.

    If both tests show no sign of the virus, this means treatment has been successful.

    Hepatitis C medicines

    Hepatitis C is treated using direct-acting antiviral (DAA) tablets.

    DAA tablets are the safest and most effective medicines for treating hepatitis C.

    They’re highly effective at clearing the infection in more than 90% of people.

    The tablets are taken for 8 to 12 weeks. The length of treatment will depend on which type of hepatitis C you have.

    Some types of hepatitis C can be treated using more than 1 type of DAA.

    NHS-approved hepatitis C medicines include:

    • sofosbuvir
    • a combination of ledipasvir and sofosbuvir
    • a combination of ombitasvir, paritaprevir and ritonavir, taken with or without dasabuvir
    • a combination of elbasvir and grazoprevir
    • a combination of sofosbuvir and velpatasvir
    • a combination of sofosbuvir, velpatasvir and voxilaprevir
    • a combination of glecaprevir and pibrentasvir
    • ribavirin

    For more information, see the NICE guidelines on:

    • sofosbuvir for treating chronic hepatitis C
    • ledipasvir-sofosbuvir for treating chronic hepatitis C
    • ombitasvir-paritaprevir-ritonavir with or without dasabuvir for treating chronic hepatitis C
    • elbasvir-grazoprevir for treating chronic hepatitis C
    • sofosbuvir-velpatasvir for treating chronic hepatitis C
    • sofosbuvir-velpatasvir-voxilaprevir for treating chronic hepatitis C
    • glecaprevir–pibrentasvir for treating chronic hepatitis C

    Side effects of treatment

    Treatments with direct-acting antivirals (DAAs) have very few side effects. Most people find DAA tablets very easy to take.

    You may feel a little sick and have trouble sleeping to begin with, but this should soon settle down.

    Your nurse or doctor should be able to suggest things to help ease any discomfort.

    You need to complete the full course of treatment to ensure you clear the hepatitis C virus from your body.

    If you have any problems with your medicines, speak to your doctor or nurse straight away.

    Side effects for each type of treatment can vary from person to person.

    For a very small number of people, more severe side effects from hepatitis C treatments may include:

    • depression
    • skin irritation
    • anxiety
    • problems sleeping (insomnia)
    • anorexia
    • tiredness caused by anaemia
    • hair loss
    • aggressive behaviour

    How effective is treatment?

    Direct-acting antivirals (DAAs) cure 9 out of 10 patients with hepatitis C.

    Successful treatment does not give you any protection against another hepatitis C infection. You can still catch it again.

    There’s no vaccine for hepatitis C.

    If treatment does not work, it may be repeated, extended, or a different combination of medicines may be tried.

    Your doctor or nurse will be able to advise you.

    Things you can do during treatment for hepatitis C

    There are some things you can do to help limit any damage to your liver and prevent the infection spreading to others.

    These can include:

    • eating a healthy, balanced diet
    • exercising regularly
    • cutting out alcohol or limiting how much you drink
    • quitting smoking
    • keeping personal items, such as toothbrushes or razors, for your own use
    • not sharing any needles or syringes with others
    • practising safer sex
    • telling sexual partners who might need to get tested

    Pregnancy and hepatitis C

    The new hepatitis C medicines have not been tested in pregnancy.

    You should not become pregnant while taking treatment as it could be harmful to unborn babies.

    If you’re pregnant, you must delay treatment until after your baby is born.

    Speak to your doctor before starting hepatitis C treatment if you’re planning to become pregnant in the near future.

    You’ll need to wait several weeks after treatment has ended before trying to get pregnant.

    Women taking ribavirin should use contraception during treatment and for another 4 months after the end of treatment.

    Men taking ribavirin should use a condom during treatment and for another 7 months after the end of treatment. This is because semen can contain ribavirin.

    If you become pregnant during treatment, speak to your doctor as soon as possible to discuss your treatment options.

    Deciding against treatment

    Some people with chronic hepatitis C decide against treatment.

    This may be because they:

    • do not have any symptoms
    • are willing to live with the risk of cirrhosis at a later date
    • do not feel the potential benefits of treatment outweigh the side effects some treatments can cause

    Your care team can give you advice about this, but the final decision about treatment will be yours.

    If you decide not to have treatment but then change your mind, you can ask to be treated at any point.

    Page last reviewed: 27 October 2021
    Next review due: 27 October 2024

    Support links

    • Home
    • Health A to Z
    • Live Well
    • Mental health
    • Care and support
    • Pregnancy
    • NHS services
    • Coronavirus (COVID-19)
    • NHS App
    • Find my NHS number
    • Your health records
    • About the NHS
    • Healthcare abroad
    • Contact us
    • Other NHS websites
    • Profile editor login
    • About us
    • Accessibility statement
    • Our policies
    • Cookies

    Conan, software package manager for C and C++ developers

    The open source, decentralized and multi-platform package
    manager to create and share all your native binaries.

    Conan 2.0 Is Out Now

    Conan is universal and portable.

    It works in all operating systems including Windows, Linux, OSX, FreeBSD, and others, and it can target any platform, including desktop, server, and cross-building for mobile (Android and iOS), as well as embedded and bare metal devices. It integrates with other tools like Docker, MinGW, WSL, and with all build systems such as CMake, MSBuild, Makefiles, Meson, SCons. It can even integrate with any proprietary build systems.

    Conan is open source and completely free.

    It has native integration with JFrog Artifactory, including the free Artifactory Community Edition for Conan, enabling developers to host their own private packages on their own server. Conan is developed by a full team of full-time maintainers who support many thousands of users, from small to big enterprises, alongside an active and awesome community.

    Conan can manage any number of different binaries.

    Not only different binaries but also different build configurations, including different architectures, compilers, compiler versions, runtimes, C++ standard library, etc. When binaries are not available for one configuration, they can be built from sources on-demand. Conan can create, upload and download binaries with the same commands and flows on every platform, saving lots of time in development and continuous integration.

    Artifactory Community Edition for C and C++

    Artifactory Community Edition (CE) for C and C++ is the recommended server for development and hosting private packages for a team or company. It is completely free, and it features a WebUI, advanced authentication and permissions, great performance and scalability, a REST API, a generic CLI tool and generic repositories to host any kind of source or binary artifact.

    ConanCenter, the place to find and share popular C and C++ Conan packages

    ConanCenter is the central repository where you can search and discover all the available open source Conan packages created by the community. It includes recipe and configuration information, and makes it easy to see package metadata in the UI. ConanCenter contains more than a thousand popular open source libraries packages, with many pre-compiled binaries for mainstream compiler versions and platforms.

    Meet the CONAN 2.0 TRIBE

    A group of more than 70 Conan expert users and contributors that helped to define Conan 2.0.

    Meet the CONAN 2.0 TRIBE

    A group of more than 70 Conan expert users and contributors that helped to define Conan 2.0.

    CUSTOMER SUCCESS STORIES
    Real-Time Innovations

    Speeding Multi-Platform Releases for Industrial IoT with Conan and Artifactory

    TomTom Navigation

    TomTom fast tracks their delivery cycle with Conan

    Real-Time Innovations

    Speeding Multi-Platform Releases for Industrial IoT with Conan and Artifactory

    TomTom Navigation

    TomTom fast tracks their delivery cycle with Conan

    Real-Time Innovations

    Speeding Multi-Platform Releases for Industrial IoT with Conan and Artifactory

    OUR USERS

    Poco

    Huawei

    Pix4D

    Keysight

    Microblink

    Mercedes Benz

    Melexis

    OpenROV

    Arxan

    Plex

    Conan has been a lifesaver in managing cross-platform packages for Imageflow. It’s flexible, addresses the hard problems of C and C++ package management head-on, and is backed by a fantastic set of developers. Don’t waste your time with alternatives; this is the real deal.

    Nathanael Jones
    Owner & Lead Software Engineer at Imazen

    TomTom

    We started to see that we could speed up our development chain by producing binary artifacts that could be shared across developers — we could actually shorten the build times because they don’t have to be built over again.

    Maikel van den Hurk
    Principal Software Engineer at TomTom

    Conan makes it easier for our many automotive GitHub Enterprise customers doing C and C++ programming to establish a continuous delivery pipeline that actually deserves that name.

    Johannes Nicolai
    Enterprise Solutions Engineer at GitHub

    Conan integration enabled a 10x reduction in our development compile-test cycle and release build times, enabling extra coding time for devs and much quicker BlinkID SDK releases. Organizing our codebase into multiple packages enabled us easier maintenance. On top of that, the dependency graph visualizer is great for every developer to see the overview of all modules/packages, as well as their individual contribution to the complete project.

    Nenad Mikša
    Compiler Whisperer at Microblink

    tanker

    I’ll simply say that I was a total n00b in build systems before, dreading to update dependencies. Conan made it easy and likeable, I’m now really interested in packaging. Weird for a C++ programmer!

    Theo Delrieu
    R&D Engineer at Tanker

    Conan’s flexibility made it possible to do something that was thought intractable; to make a modular Boost C++ Libraries distribution.

    Rene Rivera
    Boost.Build and Boost.Predef author and lead programmer at Disbelief LLC

    What is best in life? Crushing your build times, driving your semantically versioned packages before you, and not hearing the lamentations of your developers

    Daniel Greidinger
    Software Architect at Keysight Technologies

    Mercedes-Benz

    Conan has amplified our productivity, by minimizing the build times and implement full fled CI features for our C and C++ development. Its the true dependency manager for C and C++

    Siva Mandadi
    Sr Devops Lead Engineer at Mercedes-Benz R&D

    Conan brings C++ development and dependency management into the 21st century and on par with the other development eco-systems. We are currently designing this in to streamline the development of test programs for our products to help facilitate reuse and help our distributed teams develop the robust and efficient tests to guarantee the quality of our innovative products.

    Peter Tillemans
    IT Manager at Melexis

    Conan helped us with our infrastructure overhaul by reducing our full build time by over 40 minutes. That has saved us both Developer time and reduced our AWS bill.

    Derian Reuss
    DevOps Lead at Arxan Technologies

    At Pix4D, we suffered for years the pain of managing a few dozens of 3rd party dependencies with our home-grown tools. Not only developers were feeling that pain, but also the CI/CD infrastructure. We decided to give Conan a try, and it worked! It does not matter how the libraries we depend on are built or provided (CMake, autotools, pre-compiled binaries). Conan gives us the flexibility to manage C and C++ libraries of all kinds. We have Conan fully integrated in our CI system and we do pretty advanced things with it. It definitely made our life easier.

    Luis Díaz Más
    C++ Software Developer at Pix4D

    Conan arrived just in time to enable us to test multiple networking, logging, and cryptography libraries simply by adding lines to a text file. Moreover, when we did decide to master a library, we invested our time into a single cross-platform package, so our developers didn’t need to build and rebuild the library on their own. It’s revolutionized how we do rapid prototyping.

    Gerald R. Wiltse
    Manager of AppAnywhere Technology Strategy

    Conan has been a lifesaver in managing cross-platform packages for Imageflow. It’s flexible, addresses the hard problems of C and C++ package management head-on, and is backed by a fantastic set of developers. Don’t waste your time with alternatives; this is the real deal.

    Nathanael Jones
    Owner & Lead Software Engineer at Imazen

    TomTom

    We started to see that we could speed up our development chain by producing binary artifacts that could be shared across developers — we could actually shorten the build times because they don’t have to be built over again.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

https://alkogolizm.vyvod-iz-zapoya-v-stacionare-samara11.ru/