Namespaces
Variants
Actions

Talk:cpp/memory/shared ptr/make shared

From cppreference.com

Something like "Since C++11" missing? 217.13.68.110 01:07, 29 July 2016 (PDT)

added, thanks --Cubbi (talk) 05:50, 29 July 2016 (PDT)

Hi, I'm trying to get shared_ptr work with arrays like unique_ptr can but I'm failing miserably. Could someone give here an example like the one in make_unique ([1]) that actually works? Or is there a problem with the implementation of shared_ptr that currently forbids it working as the standard (C++14 onwards) asks? (Or am I misinterpreting the standard and shared_ptr is not supposed to work with arrays?) So far I can declare a shared_ptr with an array type but I cannot initialise it... :-(

std::shared_ptr<int[]>  sp1; // = new int [2]; // fails in initialisation - type mismatch
 
std::shared_ptr<int[2]> sp2; // = new int [2]; // fails in initialisation - type mismatch

Thanks.--188.29.165.104 04:35, 18 December 2016 (PST) Christos

pointer constructor for shared_ptr is explicit; you can't use copy-init regardless of what type you have. Using ...{new int[2]} works in C++17. As for make_shared, I don't think n3939 passed.. you can use boost though, as in boost::make_shared<int[2]>(); or boost::make_shared<int[]>(1,2); --Cubbi (talk) 10:08, 18 December 2016 (PST)
edit: best I can see, n3939 was reviwed in Urbana-2015, deferred to Lenexa in Cologne-2016 with a comment ("there are still pending action items from Urbana") and never came up in Lenexa? I'll ask. --Cubbi (talk) 10:15, 18 December 2016 (PST)
edit2: got a response from the n3939 author, array support for make_shared missed the C++17 deadline and will shoot for C++20. --Cubbi (talk) 11:17, 18 December 2016 (PST)
Thanks! I was trying to use g++ 6.1 (what here is offered as the most recent one) and it was failing, even with the explicit construction. I see that it works on gcc 7.0. Bizarre that this doesn't work with earlier versions - wasn't support for arrays in shared_ptr added in C++14?

Was there any reason why they decided to make the constructor explicit (when it's not in unique_ptr)? Thanks for the extremely fast and useful response (and finding out what's going on with make_shared)! Best.--188.29.164.83 14:13, 18 December 2016 (PST) Christos

support for arrays in shared_ptr is a C++17 feature (originally a library fundamentals TS feature). shared_ptr constructor from pointers was explicit from the beginning (that's how it appears in TR1), though I don't have a rationale at hand. --Cubbi (talk) 14:31, 18 December 2016 (PST)