Атрибут C++: carries_dependency (начиная с C++11)(удалён в C++26)
Указывает, что цепочка зависимостей в модели release-consume std::memory_order распространяется на входе и выходе функции, что позволяет компилятору пропускать ненужные инструкции барьера памяти.
Синтаксис
[[carries_dependency]] |
Пояснение
Этот атрибут может встречаться в двух случаях:
1) он может применяться к объявлениям параметров функции или лямбда-выражения; в этом случае он указывает, что инициализация параметра переносит зависимость на преобразование этого объекта из lvalue в 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++23 (ISO/IEC 14882:2024):
- 9.12.4 Атрибут carries dependency [dcl.attr.depend]
- Стандарт C++20 (ISO/IEC 14882:2020):
- 9.12.3 Атрибут carries dependency [dcl.attr.depend]
- Стандарт C++17 (ISO/IEC 14882:2017):
- 10.6.3 Атрибут carries dependency [dcl.attr.depend]
- Стандарт C++14 (ISO/IEC 14882:2014):
- 7.6.4 Атрибут carries dependency [dcl.attr.depend]
- Стандарт C++11 (ISO/IEC 14882:2011):
- 7.6.4 Атрибут carries dependency [dcl.attr.depend]
См. также
|
(C++11)(устарел в C++26) | удаляет указанный объект из дерева зависимостей std::memory_order_consume (шаблон функции) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/language/attributes/carries_dependency