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

我最近发现使用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

点赞