【问题标题】:Warning: ignoring attributes on template argument... in declaration of std::unique_ptr (-Wignored-attributes)警告:忽略模板参数上的属性...在 std::unique_ptr (-Wignored-attributes) 的声明中
【发布时间】:2020-06-16 15:30:03
【问题描述】:

使用here解释的模式如下:

auto action = 
  std::unique_ptr< posix_spawn_file_actions_t, decltype(&posix_spawn_file_actions_destroy) > 
  { new posix_spawn_file_actions_t(), posix_spawn_file_actions_destroy };

在 gcc 中触发 [-Wignored-attributes] v10.1.0 -std=c++20:

warning: ignoring attributes on template argument ‘int (*)(posix_spawn_file_actions_t*) noexcept’
|         std::unique_ptr<posix_spawn_file_actions_t, decltype(&posix_spawn_file_actions_destroy)>
|                                                                                                ^

这是为什么呢?应该忽略还是有办法调整代码?

【问题讨论】:

    标签: c++ posix unique-ptr gcc-warning


    【解决方案1】:

    这是说你忽略了函数指针不抛出的事实。

    您的代码还有其他错误,例如新的指针未被删除清除。

    或更高版本我使用

    template<auto x> using kval_t=std::intergral_constant<std::decay_t<decltype(x)>,x>;
    template<auto x> constexpr kval_t<x> kval={};
    

    然后你可以:

    auto action = 
      std::unique_ptr< posix_spawn_file_actions_t, kval_t<posix_spawn_file_actions_destroy> >  =
         { new posix_spawn_file_actions_t() };
    

    但是new 这里可能是创建posix_spawn_file_actions_t 的错误方法。

    这会将函数指针存储在编译时间常数中,并且可能会消除该警告。

    【讨论】:

    • 好的,根据unix.stackexchange.com/a/479567/82783posix_spawn_file_actions_destroy可以作用于分配给posix_spawn_file_actions_t的堆栈地址。那么我可能应该完全摆脱unique_ptr,尽管仍然有可能无法拨打posix_spawn_file_actions_destroy...啊,我讨厌C在C++中混合
    • @dario 如果你想避免堆分配,你想要一个可以为空的句柄,比如en.cppreference.com/w/cpp/named_req/NullablePointer
    • 谢谢,我不认为我真的需要那个。 C 接口通常提供一个函数,该函数返回一个分配的指针,并在完成后提供第二个函数来释放它。我喜欢将这两个包装在一个智能指针中执行 RAII,但我没有注意到这些 posix 函数略有不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    相关资源
    最近更新 更多