jeudi 5 mars 2020

overloading global function with unique_ptr and raw pointers

I've been developing a feature in c++, that is using some legacy code written C language.

I've been facing compiler error with overloaded versions of a function that either takes unique_ptr or a raw pointer of the same type.

Simplified version of my code is given below:

class A{
public:
    A():mDummy(0) { }
    ~A()=default;
    int mDummy;
};

void handleObj(std::unique_ptr<A> ap){
    std::cout<<ap->mDummy<<'\n';
}

void handleObj(A* ap){
    std::cout<<ap->mDummy<<'\n';
}

int main(){

    std::unique_ptr<A> obj{new A()};
    std::thread t1{handleObj, std::move(obj)};

    A* obj2{ new A()};
    std::thread t2{handleObj, obj2};

    if(t1.joinable())
        t1.join();

    if(t2.joinable())
        t2.join();
}

when compiled getting this error:

/Users/dsatram/Desktop/overload_uniquePtr_rawPtr/main.cpp:29:17: error: no matching constructor for initialization of 'std::thread'
    std::thread t1{handleObj, std::move(obj)};
                ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:359:9: note: candidate template ignored: couldn't infer template argument '_Fp'
thread::thread(_Fp&& __f, _Args&&... __args)
        ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:289:5: note: candidate constructor not viable: requires 1 argument, but 2 were provided
    thread(const thread&);
    ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:315:5: note: candidate constructor not viable: requires single argument '__t', but 2 arguments were provided
    thread(thread&& __t) _NOEXCEPT : __t_(__t.__t_) {__t.__t_ = _LIBCPP_NULL_THREAD;}
    ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:296:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
    thread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {}

Can some body help me understand whats wrong here?

Aucun commentaire:

Enregistrer un commentaire