0

I need a list of unique pointers to ints (I need the underlying int arrays because of MPI compatibility, they are buffers that are getting tracked for work done). I have a workaround but would like to understand what is happening

std::list<std::unique_ptr<int[]>> const buf_send2 = std::list<std::unique_ptr<int[]>>{std::make_unique<int[]>(this->buffersize)}; 

Doesn't work as an initializer in the class because of

 /usr/include/c++/15.2.1/bits/new_allocator.h:191:11: error: use of deleted function ? ‘std::unique_ptr<_Tp [], _Dp>::unique_ptr(const std::unique_ptr<_Tp [], _Dp>&) [with _Tp = int; _Dp = std::default_delete<int []>]’ 191 | { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); } | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

I know ahead of time how many buffers I need in this case (or specifically the maximum), so I can just use an array but this is exposing my weaknesses as a C++ programmer and wanted to try and understand what was happening.

This works fairly straightforwardly with non-array unique pointers can array unique pointers not be moved? Is there a way of doing this correctly?

7
  • 5
    Why not use std::vector<int> for the buffers and then use .data() method to pass to C API if needed ? Commented 3 hours ago
  • Relevant: stackoverflow.com/q/9618268/580083. You can only copy from std::initializer_list, but std::unique_ptr is non-copyable. Simple demo: godbolt.org/z/d8xfExoj3. Commented 2 hours ago
  • It is trying to call a copy constructor, because that's how initializer_list works. Why? I don't know, it just does. Commented 2 hours ago
  • 1
    "This works fairly straightforwardly with non-array unique pointers" -- Do you have an example of this? I tried adapting the code in the question, but got the same error for std::unique_ptr<int>. Commented 2 hours ago
  • Why do you construct a temporary list, then construct another list based upon the first? While the compiler will optimize away the second construction, the result is more typing, and is harder to read, than simply std::list<std::unique_ptr<int[]>> const buf_send2{std::make_unique<int[]>(this->buffersize)};. Commented 2 hours ago

1 Answer 1

-2
#include <list> #include <memory> struct S { std::list<std::unique_ptr<int[]>> buf_send2; int buffersize; S(int n): buffersize(n) { buf_send2.emplace_back(std::make_unique<int[]>(buffersize)); } }; 
New contributor
Deepanshu Bora is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.