3
struct FrameBufferAttachment
    {
        std::unique_ptr<Image> AttachmentImage;
        //std::unique_ptr<ImageView> AttachmentImageView;
        AttachmentType Type = AttachmentType::Color;
    };

    struct FrameBuffer
    {
        //std::vector< FrameBufferAttachment> FrameBufferColorAttachments;
        FrameBufferAttachment DepthStencilAttachment;

        VkFramebuffer framebuffer;
    };

    std::vector<FrameBuffer> frameBuffers;

I need help with this as I can't figure out what the problem is. I get error C2672: 'std::construct_at': no matching overloaded function found but if I comment out FrameBufferAttachment DepthStencilAttachment; then the error goes away.

If I change the unique pointer to a raw pointer then the error goes away too. So I must be using the unique pointer wrong.

This is how I use it in code

FrameBuffer frameBuffer;
frameBuffers.push_back(frameBuffer);

If I don't push it then no error.

Any ideas?

Sean Nolan
  • 43
  • 3
  • Please add the code where you construct the `std::unique_ptr` for others to better understand the problem – thedemons Oct 20 '22 at 01:03
  • Does this answer your question? [Adding struct items containing a unique\_ptr to an stl container](https://stackoverflow.com/questions/19728164/adding-struct-items-containing-a-unique-ptr-to-an-stl-container) – Retired Ninja Oct 20 '22 at 01:22

1 Answers1

2

std::unique_ptr is unique, and could not be copied.

But I didn't copy anything, and what does this have to do with the error? You may wonder.

Yes, here comes the tricky part of std::vector<>::push_back, it will actually copy the object instead of constructing the object on its array, therefore the object gets constructed twice. If anything, that is an unnecessary waste of time and resources.

You can try to copy FrameBuffer and see that it won't be compiled:

FrameBuffer frameBuffer;
FrameBuffer frameBuffer_copy = frameBuffer;

For most cases, prefer to use std::vector<>::emplace_back, this will construct the object on the vector itself rather than wasting time making a copy of it. See this question.

Edit: As @user17732522 mentioned, this will only work for C++17 and above:

FrameBuffer& frameBuffer = frameBuffers.emplace_back();

Before C++17:

frameBuffers.emplace_back();
FrameBuffer& frameBuffer = frameBuffers.back();
thedemons
  • 1,139
  • 2
  • 9
  • 25
  • 1
    Beware though that `emplace_back` returns the reference only since C++17. Before that you need to get the element afterwards with `.back()`. – user17732522 Oct 20 '22 at 01:30