一个std :: shared_ptr <>的c - std :: tuple <>不起作用?

一个std :: shared_ptr <>的c - std :: tuple <>不起作用?,第1张

概述我最近发现使用std :: tuple<>的问题只有一个元素.我创建了一个类型擦除类,并保留了N个引用计数对象.但是,如果引用计数对象是std :: tuple<>中唯一的对象,则不会保留它. 难道我做错了什么? class token {public: template<typename... Types> token(Types... types) : _self(std::make 我最近发现使用std :: tuple<>的问题只有一个元素.我创建了一个类型擦除类,并保留了N个引用计数对象.但是,如果引用计数对象是std :: tuple<>中唯一的对象,则不会保留它.

难道我做错了什么?

class token {public:  template<typename... Types>  token(Types... types) : _self(std::make_shared<const std::tuple<Types...>>(std::make_tuple(std::move(types)...))) {}  // Why do I need this special version of the constructor?  // Uncomment and the code will work!  //template<typename T>  //token(T t) : _self(std::make_shared<const T>(std::move(t))) {}private:  std::shared_ptr<const voID> _self;};

示例(使用Xcode 8.0测试):

token make_token() {  std::shared_ptr<int> shared(new int(),[](int* i) {    // Called immediately if using only tuple constructor!  });  return token(shared);}token my_token = make_token(); // std::shared_ptr<> is already gone!
解决方法 从我的角度来看,你的代码应该可以正常运行,msvc和gcc似乎在 this snippet中同意我的观点.来自T.C.评论,这看起来像clang的真正问题,并在clang trunk中修复

作为现在的解决方法,我建议采用这种方法,(special_decay_t取自cppreference):

#include <iostream>#include <tuple>#include <memory>template <class T>struct unwrap_refwrapper{    using type = T;};template <class T>struct unwrap_refwrapper<std::reference_wrapper<T>>{    using type = T&;};template <class T>using special_decay_t = typename unwrap_refwrapper<typename std::decay<T>::type>::type;class token {public:  template<typename... Types>  token(Types&&... types) : _self(std::make_shared<std::tuple<special_decay_t<Types>...>>(std::forward<Types>(types)...)) {}private:  std::shared_ptr<voID> _self;};token make_token() {  return token(std::shared_ptr<int>(new int(),[](int* i) {    std::cout << "freed\n";    delete i;  }));}int main(){    token my_token = make_token();    std::cout << __liNE__ << '\n';}

见demo

总结

以上是内存溢出为你收集整理的一个std :: shared_ptr <>的c - std :: tuple <>不起作用?全部内容,希望文章能够帮你解决一个std :: shared_ptr <>的c - std :: tuple <>不起作用?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1228439.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存