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

Differences between assignment constructor and others in c++

std::shared_ptr<Res> ptr=new Res();

the above statement doesn’t work.
Compiler complains there’s no viable conversion….
while the below works

std::shared_ptr<Res> ptr{new Res()} ;

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

explain how it’s possible?!

Actually what’s the main differences in constructor{uniform, parentheses, assignments}?

>Solution :

The constructor of std::shared_ptr taking a raw pointer is marked as explicit; that’s why = does not allow you to invoke this constructor.

Using std::shared_ptr<Res> ptr{new Res()}; is syntax that allows you to call the an explicit constructor to initialize the variable.

std::shared_ptr<Res> ptr=new Res();

would invoke an implicit constructor taking a pointer to Res as single parameter, but not an explicit one.

Here’s a simplified example using a custom class with no assignment operators and just a single constructor:

class Test
{
public:
    Test(int i) { }

    // mark all automatically generated constructors and assignment operators as deleted
    Test(Test&&) = delete;
    Test& operator=(Test&&) = delete;
};

int main()
{
    Test t = 1;
}

Now change the constructor to

explicit Test(int i) { }

and the main function will no longer compile; the following alternatives would still be viable:

Test t(1);
Test t2{1};
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