HowdoIunderstandhowstd::make_sharedworks?
I came across an elegant line of reading a binary file into a vector like this (that works):
std::ifstream ifs("myfile.bin", std::ios::binary);
std::vector<char> buffer(std::istreambuf_iterator<char>(ifs), {});
Instead since I want my vector to be a shared pointer I write:
std::ifstream ifs("myfile.bin", std::ios::binary);
auto sp = std::make_shared<std::vector<char>>(std::istreambuf_iterator<char>(ifs), {});
I.e just pass the vector constructor arguments to make_shared (as I usually do to create any shared pointer of any objects).
But I get: error: no matching function for call to 'make_shared'?
Detailed output:
/usr/include/c++/11.1.0/bits/shared_ptr.h|873 col 5| note: candidate template ignored: substitution failure [with _Tp = std::vector<char, std::allocator>]: deduced incomplete pack <std::istreambuf_iterator<char, std::char_traits >, (no value)> for template parameter '_Args'
|| make_shared(_Args&&... __args)
回答
这将起作用:
std::ifstream ifs("myfile.bin", std::ios::binary);
auto sp = std::make_shared<std::vector<char>>(std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>{});
这是因为您正在使用这个可变参数模板:
template<class T, class... Args>
shared_ptr<T> make_shared( Args&&... args );
如果不是手动实例化,则每个参数类型都必须是可推导的。“{}”不允许参数推导,因此会出现编译器错误。可悲的是,您还可以显式实例化模板:
auto sp = std::make_shared<std::vector<char>, std::istreambuf_iterator<char>,
std::istreambuf_iterator<char>>({ifs}, {});
在这两种情况下,迭代器的类型别名可能会提高可读性(using InputIt = std::istreambuf_iterator<char>;或类似的东西)。