Reputation: 33
I show you the code directly.
#include <iostream>
#include <stdio.h>
class A {
public:
A(const std::string& name){
std::string aname = "HAHA_" + name;
std::cout << aname << std::endl;
}
~A(){
std::cout << "Done." << std::endl;
}
};
int main() {
size_t len = 5;
char szTmp[30] ={0};
snprintf(szTmp,sizeof(szTmp),"Getlist_V2_%zd",len);
A a(std::string(szTmp));
return 0;
}
The expected results are as follows:
HAHA_Getlist_V2_5
Done.
But It outputs nothing at all. When I replace A a(std::string(szTmp));
with
A a(szTmp);
,erverything is ok. It confused me for a long time.
Upvotes: 3
Views: 75
Reputation: 385098
A a(std::string(szTmp));
This is a function declaration, believe it or not! So, no A
is constructed.
Instead, write this:
A a{std::string(szTmp)};
Or, since an implicit conversion to std::string
exists, either of the following will suffice:
A a{szTmp};
A a(szTmp);
Upvotes: 7