Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with passing std::unique_ptr #93

Open
lordnn opened this issue Nov 7, 2021 · 3 comments
Open

Problem with passing std::unique_ptr #93

lordnn opened this issue Nov 7, 2021 · 3 comments

Comments

@lordnn
Copy link

lordnn commented Nov 7, 2021

#include "ThreadPool.h"
#include <stdio.h>

class Foo {
public:
    Foo();
    void Process(std::unique_ptr<uint16_t[]> im);
private:
    void ProcessImpl(std::unique_ptr<uint16_t[]> im);
    ThreadPool t;
};

Foo::Foo() : t(4) {
}

void Foo::Process(std::unique_ptr<uint16_t[]> im) {
#if 0
    ProcessImpl(std::move(im));
#else
    t.enqueue(&Foo::ProcessImpl, this, std::move(im));
#endif
}

void Foo::ProcessImpl(std::unique_ptr<uint16_t[]> im) {
    printf("%p\n", im.get());
}

int main()
{
    Foo f;
    auto p = std::make_unique<uint16_t[]>(100);
    printf("%p\n", p.get());

    f.Process(std::move(p));
}

This doesn't compile.

@lasorda
Copy link

lasorda commented Mar 16, 2022

this worked

#include "ThreadPool.h"
#include <cstdint>
#include <stdio.h>

class Foo {
public:
    Foo();
    void Process(std::unique_ptr<uint16_t[]> im);
private:
    void ProcessImpl(std::shared_ptr<uint16_t[]> im);
    ThreadPool t;
};

Foo::Foo() : t(4) {
}

void Foo::Process(std::unique_ptr<uint16_t[]> im) {
#if 0
    ProcessImpl(std::move(im));
#else
    std::shared_ptr<uint16_t[]> p = std::move(im);
    t.enqueue(&Foo::ProcessImpl, this, std::move(p));
#endif
}

void Foo::ProcessImpl(std::shared_ptr<uint16_t[]> im) {
    printf("%p %ld\n", im.get(), im.use_count());
}

int main()
{
    Foo f;
    auto p = std::make_unique<uint16_t[]>(100);
    printf("%p\n", p.get());

    f.Process(std::move(p));
}

out:

0x10fe3f0
0x10fe3f0 2

https://stackoverflow.com/questions/20268482/binding-functions-with-unique-ptr-arguments-to-stdfunctionvoid

@lordnn
Copy link
Author

lordnn commented Apr 11, 2022

So, problem with passing std::unique_ptr still here. :(

@love1angel
Copy link

love1angel commented Feb 2, 2023

@lordnn change fn Process like this will use

void Foo::Process(std::unique_ptr<uint16_t[]> im) {
#if 0
    ProcessImpl(std::move(im));
#else
    auto f = [this, p = std::move(im)]() mutable {
        this->ProcessImpl(std::move(p));
    };
    t.enqueue(std::move(f));
#endif
}

explaining are here https://stackoverflow.com/questions/8640393/move-capture-in-lambda/20669290#20669290

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants