C++ атрибут: carries_dependency (с C++11)
Указывает, что цепочка зависимостей при выделении и использовании std::memory_order распространяется внутрь и наружу функции, что позволяет компилятору пропускать ненужные инструкции памяти.
Синтаксис
[[carries_dependency]] |
Объяснение
Этот атрибут может использоваться в двух ситуациях:
1) он может применяться к объявлениям параметров функции или лямбда-выражений, в этом случае он указывает, что инициализация параметра передаёт зависимость в преобразование lvalue-to-rvalue этого объекта.
2) он может применяться к объявлению функции в целом, в этом случае он указывает, что возвращаемое значение несёт зависимость от вычисления выражения вызова функции.
Этот атрибут должен присутствовать в первом объявлении функции или одного из её параметров в любом модуле трансляции. Если он не используется в первом объявлении функции или одного из её параметров в другом модуле трансляции, программа некорректна; диагностика не требуется.
Пример
Скопировано почти без изменений с SO.
#include <atomic>
#include <iostream>
void print(int* val)
{
std::cout << *val << std::endl;
}
void print2(int* val [[carries_dependency]])
{
std::cout << *val << std::endl;
}
int main()
{
int x{42};
std::atomic<int*> p = &x;
int* local = p.load(std::memory_order_consume);
if (local)
{
// The dependency is explicit, so the compiler knows that local is
// dereferenced, and that it must ensure that the dependency chain
// is preserved in order to avoid a fence (on some architectures).
std::cout << *local << std::endl;
}
if (local)
{
// The definition of print is opaque (assuming it is not inlined),
// so the compiler must issue a fence in order to ensure that
// reading *p in print returns the correct value.
print(local);
}
if (local)
{
// The compiler can assume that although print2 is also opaque then
// the dependency from the parameter to the dereferenced value is
// preserved in the instruction stream, and no fence is necessary (on
// some architectures). Obviously, the definition of print2 must actually
// preserve this dependency, so the attribute will also impact the
// generated code for print2.
print2(local);
}
}Возможный вывод:
42 42 42
См. также
|
(C++11) | удаляет указанный объект из std::memory_order_consume дерева зависимостей (функция-шаблон) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/language/attributes/carries_dependency