c++ - 将 char* 转换为字符串

标签 c++

我有以下代码:

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    string &s1 = argv[0];           // error
    const string &s2 = argv[0];     // ok

    argv[0] = "abc";
    cout << argv[0] << endl;        // prints "abc"
    cout << s2 << endl;             // prints program name
}

我收到以下关于 s1 的错误:

invalid initialization of reference of type 'std::string& {aka std::basic_string<char>&}' from expression of type 'char*'

那为什么编译器接受s2呢?

有趣的是,当我为 argv[0] 分配一个新值时,s2 并没有改变。编译器是否忽略它是一个引用并复制该值?为什么会这样?

我在 Code::Blocks 16.01 (mingw) 中写的。使用/不使用 -std=c++11 也会发生同样的情况。

最佳答案

Then why does the compiler accept s2?

因为常量引用可以绑定(bind)到一个临时引用,并且 std::string 有一个构造函数可以将 char * 作为参数。

该赋值构造了一个所谓的“临时”对象,并将常量引用绑定(bind)到它。

Interestingly, when I assign a new value to argv[0] then s2 does not change.

为什么要改变? s2 是一个单独的对象。 std::string 对象不维护指向创建它的 char * 的指针。有许多方法可以创建 std::string。实际字符串归对象所有。如果 std::string 是从文字字符串构造的,它会被复制到 std::string 中。因此,如果文字字符串来自缓冲区,并且缓冲区随后被修改,则对 std::string 没有影响。

关于c++ - 将 char* 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39557811/

相关文章:

c++ - 为什么 boost::spirit 将 foo123 与 (+alpha | +alnum) 语法匹配?

c++ - 猜测运行时函数的返回类型

c++ - 检查类是否继承自模板的任何模板实例化

C++ 错误 : Function 'get_time' could not be resolved - Ubuntu g++

c++ - 我应该总是继续使用 `sink` 构造函数或 setter 参数吗?

c++ - 不同格式的 GUID 和 CLSID?

c++ - 如何使用 C++ 在 Windows 上创建具有 UNICODE 路径的文件

c++ - 使用 Qt 和 C++ 连续绘制对象

C++别名具有相同名称的类型

c++ - Win32 中是否有检测用户何时更改区域设置的消息或通知?