开发者

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 a std::string, not an std::string.

  • Passing p->data() to cout would be dangerous given that data() returns a char array without a null terminator, unlike string::c_str(). I'd suggest you just use

    cout << *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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜