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

vic*_*ico 21 c++ visual-c++

在我的代码的一个功能中,我发现了一个错误.它写道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;
}
Run Code Online (Sandbox Code Playgroud)

代码编译没有错误.为什么编译?什么std:string意思呢?

Sin*_*all 20

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

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

显然这是一个错字.您的代码编译因为using namespace std;using std::string在上面某处使用过.否则,您将收到"未在此范围内声明字符串"错误.


Nik*_*kko 6

我认为它编译是因为臭名昭着的"using namespace std;"指令在文件上面使用过(或者更糟糕的是,在另一个包含的文件中).

因此编译器将" std:"视为goto标签,并使用(std::)string因为使用了"using namespace std".

通常在现代编译器上,您可能会收到警告,例如(在gcc中):

  warning: label ‘std’ defined but not used
Run Code Online (Sandbox Code Playgroud)


Sha*_*our 5

std:被用作标签,可以用作goto的目标.您的代码中的某个位置必须有一个using指令:

using std::string;
Run Code Online (Sandbox Code Playgroud)

要么:

using namespace std; 
Run Code Online (Sandbox Code Playgroud)

另请参阅为什么"使用命名空间std;"被认为是不好的做法?.

这证明了使用警告重要性.我可以使用正确的标志来获取Visual Studio,gcc和clang来警告这一点.对于Visual Studio使用,/W3会发出以下警告(请参见实时):

警告C4102:'std':未引用的标签

对于此代码:

#include <string>

using std::string ;

int main()
{
    std:string s1 ;
}
Run Code Online (Sandbox Code Playgroud)

对于gcc和clang使用-Wall就足够了,对于gcc我收到以下内容:

warning: label 'std' defined but not used [-Wunused-label]
 std:string s1 ;
 ^
Run Code Online (Sandbox Code Playgroud)

和clang发出类似的警告.