string和const char *和.c_str()?

问题描述:

我得到一个奇怪的问题,我想知道为什么它的行为像这样。我有一个类,其中有一个成员函数返回 std :: string 。我的目标是将这个字符串转换为 const char * ,所以我做了下面的

I'm getting a weird problem and I want to know why it behaves like that. I have a class in which there is a member function that returns std::string. My goal to convert this string to const char*, so I did the following

    const char* c;
    c = robot.pose_Str().c_str();  // is this safe??????
    udp_slave.sendData(c);

问题是我在主端有一个奇怪的字符。但是,如果我执行以下操作:

The problem is I'm getting a weird character in Master side. However, if I do the following

    const char* c;
    std::string data(robot.pose_Str());
    c = data.c_str();
    udp_slave.sendData(c);

我得到了我的期望。我的问题是上述两种方法之间的区别是什么?

I'm getting what I'm expecting. My question is what is the difference between the two aforementioned methods?

这是一个指向临时的问题。
如果按值返回但不存储 string ,它将在下一个序列点(分号)处消失。

It's a matter of pointing to a temporary. If you return by value but don't store the string, it disappears by the next sequence point (the semicolon).

如果你将它存储在一个变量中,那么指针指向的是在你的udp发送期间实际存在的东西

If you store it in a variable, then the pointer is pointing to something that actually exists for the duration of your udp send

int f() { return 2; }


int*p = &f();

现在看起来傻了,不是吗?您正在指向正从从 f 复制回来的值。你不知道它要住多久。

Now that seems silly on its face, doesn't it? You are pointing at a value that is being copied back from f. You have no idea how long it's going to live.

您的字符串是一样的。