a pointer bound to a function may only be used to call a function
I've just moved from char arrays to std::string and I've already ran into a problem, I'm probably doing something extremely stupid, feel free to ridicule:
int main()
{
string * p = new string;
memset(p, 0, sizeof(string));
expected_exepath(p);
cout << p->data;
delete p;
}
The error is in p->data, which says "a pointer bound to a function may only be used to call a 开发者_JAVA百科function".. p is std::string, so I don't see why it thinks I'm trying to call a function.
Because data is a function, not a data member. More importantly, half the point of std::string
is that it's a value. You shouldn't use new
unless you have an extremely good reason- allocate on the stack, or if you must dynamically allocate use a container or smart pointer.
Also: Do not ever, ever, ever memset UDTs like that. They take care of their own internal state, all the time, and do not mess with it.
The error is in p->data, which says "a pointer bound to a function may only be used to call a function".. p is std::string, so I don't see why it thinks I'm trying to call a function.
A few points:
string::data()
is a function, hence that error message is entirely appropriate.p
is a pointer to astd::string
, not anstd::string
.Passing
p->data()
tocout
would be dangerous given thatdata()
returns a char array without a null terminator, unlikestring::c_str()
. I'd suggest you just usecout << *p;
...instead.
If expected_exepath
takes a std::string*
argument, then I'd suggest re-writing your function like this:
int main()
{
string p;
expected_exepath(&p);
cout << p;
}
cout << p->data;
string::data()
is a function, not a data member. You need to call it, not just dereference it. Like this:
cout << p->data();
I'd like to provide another possible mistake that cause the same error message although not related to your specific question.
It's when you use vector.emplace_back{.. , ..}
instead of vector.emplace_back(.. , ..)
.
Hope maybe someone making this mistake like me does not get confused for hours.
精彩评论