我有以下代码:
#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/