Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

error with vector, unique_ptr, and push_back

I am learning smart pointers, with the following example test.cpp

#include<iostream>
#include<vector>
#include<memory>

struct abstractShape
{
    virtual void Print() const=0;
};

struct Square: public abstractShape
{
    void Print() const override{
        std::cout<<"Square\n";
    }
};

int main(){
    std::vector<std::unique_ptr<abstractShape>> shapes;
    shapes.push_back(new Square);

    return 0;
}

The above code has a compilation error "c++ -std=c++11 test.cpp":

smart_pointers_2.cpp:19:12: error: no matching member function for call to 'push_back'
    shapes.push_back(new Square);

Could someone help explain the error to me? By the way, when I change push_back to emplace_back, the compiler only gives a warning.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

push_back expects an std::unique_ptr, when passing raw pointer like new Square, which is considered as copy-initialization, the raw pointer needs to be converted to std::unique_ptr implicitly. The implicit conversion fails because std::unique_ptr‘s conversion constructor from raw pointer is marked as explicit.

emplace_back works because it forwards arguments to the constructor of std::unique_ptr and construct element in direct-initialization form, which considers explicit conversion constructors.

The arguments args… are forwarded to the constructor as std::forward<Args>(args)....

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading