'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()} ;
explain how it's possible?!
Actually what's the main differences in constructor{uniform, parentheses, assignments}?
Solution 1:[1]
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};
Solution 2:[2]
Because in this instance, you're using C++ copy initialization.
In order for this to work properly, the Res type needs a proper copy constructor non-explicit constructor.
In C++, explicit constructors are not considered when using copy initialization.
This page was helpful to review: https://en.cppreference.com/w/cpp/language/copy_initialization
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
