-
May 23rd, 2024, 01:49 AM
#1
Why in one case, copy Ctor is called, while in another case, another Ctor is called?
This is the common code snippet for two cases:
Code:
#include <string>
class A {
public:
//string Ctor
A(const std::string& s = std::string()) : ps(new std::string(s)) { }
//Copy Ctor
A(const A& p) : ps(new std::string(*p.ps)), i(p.i) { }
~A() { delete ps; }
private:
std::string* ps;
int i;
};
Below is case 1:
I was told by someone that the compiler would do the following steps:
1) Implicitly convert "abc" to a temporary std::string object.
2) Implicitly convert the temporary std::string object to a temporary A object.
3) Call the copy Ctor with the temporary A object to construct v.
Because there are two implicitly conversions before the copy Ctor function, the compiler reports an error (cannot convert from 'const char [4]' to 'A').
Below is case 2:
Code:
A v = std::string("abc");
From the step by step debugging, I can figure out that the compiler would do the following steps:
1) Explicitly convert "abc" to a temporary std::string object.
2) Call the string Ctor with the temporary std::string object to construct v.
My question is as follows: After step 1) of both cases, we got a temporary std::string object. I cannot see any differences at this point between two cases. But after that, two cases run in different execution paths as detailed in above steps. Why the difference after the same temporary std::string object is obtained? Thanks.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|