std:string和std::string之间的区别

22

在我的代码中的一个函数中,我发现了一个 bug。它被写成了 std:string :

const std::string currentDateTime() {
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    //strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
    strftime(buf, sizeof(buf), "%Y%m%d%X", &tstruct);

    std:string str = buf;

    str.erase(std::remove(str.begin(), str.end(), ':'), str.end());
    return str;
}

代码编译没有错误。为什么它能够编译通过?那么std:string是什么意思呢?


9
"std:"是一个标签,必须在某个地方使用它。 - Shafik Yaghmour
2
这段代码只有在使用"using namespace std"的情况下才能正常工作,但我个人认为这种做法不好。否则,除非已经定义了类型string,否则编译时会捕获到错误。 - Devolus
2
@Devolus,你也可以使用std::string来实现相同的效果。 - dascandy
1
无论是clang还是gcc都会为此提供未使用标签警告。 - Shafik Yaghmour
最近我在同事编写的代码中发现并修复了同样的错误。Bug #1出现在包含文件中,有一行using namespace std; 本不该存在于那里。修复了Bug #1后编译失败了,报告了Bug #2 std::string 的问题。 - JSF
3个回答

20

它被解释为可以与goto一起使用的标签。

int main()
{
    //label to jump to:
    label_name:
    //some code
    <..>
    //some code
    goto label_name;//jump to the line with the lable
}

很显然那是一个错别字。你的代码编译成功是因为之前某处使用了using namespace std;using std::string,否则你就会收到"string was not declared in this scope"的错误信息。


6
我认为编译通过是因为文件中使用了臭名昭著的"using namespace std;"指令(或更糟的是在另一个包含的文件中使用)。因此,编译器将“std:”视为goto标签,并使用(std::)string,因为使用了“using namespace std”。通常,在现代编译器上,你可能会收到警告,类似于(在gcc中):
  warning: label ‘std’ defined but not used

1
这个答案有几个问题,using namespace std;不是唯一的出现方式,尽管gcc可以为此发出警告,但OP标记了Visual C++的问题,并且警告不是自动的,您需要打开它们。如果它们是自动的,OP将会发现问题并且永远不会问问题。因此,问题的根源在于没有打开警告。 - Shafik Yaghmour

6

std:被用作一个标签,可以作为goto的目标使用。在您的代码中必须有一个using指令,可以放在以下位置:

using std::string;

或者:

using namespace std; 

此外,请查看为什么认为“using namespace std;”是不好的实践方式?
这展示了使用警告的重要性。使用正确的标志,我可以让Visual Studio、gcc和clang进行警告。对于Visual Studio,使用/W3给出以下警告(现场查看):

警告 C4102: “std” : 未引用的标签

对于以下代码:
#include <string>

using std::string ;

int main()
{
    std:string s1 ;
}

对于使用gcc和clang编译器的情况,使用-Wall可以满足要求。对于gcc编译器,我收到以下信息:

warning: label 'std' defined but not used [-Wunused-label]
 std:string s1 ;
 ^

来自clang的类似警告。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接