c++ - 为什么 msvc 让我这样做而不是 gcc/g++?

标签 c++ visual-c++ gcc

在 msvc 中,我有这样的函数并且它可以构建,但在 gcc 中它不喜欢它。

void classname::a(std::string &text)
{
    stdStringFromClass = text;
}

void classname::b(char *text)
{
    a(std::string(text));
}

这里的问题出在 &,我认为 gcc 很担心,因为我刚刚创建了那个 std::string,通过引用传递是有风险的,所以它没有构建,但 msvc 甚至没有警告我。

为什么 c++ 对 gcc 不正确我一直听说 msvc 比 gcc 更严格。

谢谢

错误

AguiWidgetBase.cpp: In member function ‘void AguiWidgetBase::setText(char*)’:
AguiWidgetBase.cpp:91:27: error: no matching function for call to ‘AguiWidgetBase::setText(std::string)’
AguiWidgetBase.cpp:80:6: note: candidates are: void AguiWidgetBase::setText(std::string&)
AguiWidgetBase.cpp:88:6: note:                 void AguiWidgetBase::setText(char*)

这样可以吗?

void classname::a(std::string &text)
{
    stdStringFromClass = text;
}

void classname::b(char *text)
{
   std::string k = text;
    a(k);
}

最佳答案

我认为这是 Visual Studio 从很久以前就支持的旧编译器扩展,但为了兼容性,它在现代 Visual C++ 中保留。尝试禁用编译器扩展(/Za 标志),看看会发生什么。

或者,使用 /W4 标志来获得最大警告,它应该会提示:

warning C4239: nonstandard extension used

在 GCC 上我得到常量引用错误:

error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘std::string’

关于c++ - 为什么 msvc 让我这样做而不是 gcc/g++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3897702/

相关文章:

c++ - 如何在编译时检查像 "#define VERSION 3.1.4"这样的值?

c++ - 来自字符串 C++ 的唯一单词集

编译 const GdkPixdata : "error: initializer element is not constant"

c - 获取编译器理解的宏扩展值

c - 如何解决链接描述文件中的错误?

linux - 如何使用相对路径从共享库链接到共享库?

c++ - 如何在不使用拷贝的情况下更改 QJson 层次结构中的 QJsonObject 值?

c++ - 在 ifstream 中使用运算符 '>>' 的编译器错误

c++ - 涉及 const 时无法特化模板

c++ - C++中的指针赋值。 (指向指针的指针位于 LHS 上)