为什么当作为常量字符* 返回时会在此处创建临时字符串?[斯特劳斯特鲁普的书例]
Why are temporary strings created here when returned as const char* ? [Stroustrup's book example]
我正在尝试从初学者的书中理解以下代码。(编辑:"使用 C++ 的编程原理和实践"第 1085 页)我不太明白为什么根据评论制作临时字符串。
const char* string_tbl[ ] = { "Mozart", "Grieg", "Haydn", "Chopin" };
const char* f(int i) { return string_tbl[i]; }
void g(string s){}
void h()
{
const string& r = f(0); // bind temporary string to r
g(f(1)); // make a temporary string and pass it
string s = f(2); // initialize s from temporary string
cout << "f(3): " << f(3) // make a temporary string and pass it
<<" s: " << s
<< " r: " << r << 'n';
}
f()
返回一个指向常量字符的指针,对吧?
const string& r = f(0);
不应该为引用变量分配一个"指向字符的指针"(在本例中为全局数组中的字符串文字)以便可以使用 r[] 等访问原始变量(只读)吗?
g(f(1));
传递一个指针指向g()
然后用指针初始化string s
的位置?
我错过了什么?const char* 在从函数返回时是否总是生成临时字符串?
有一个隐式转换,代码
string s = f(2);
等于
string s = string(f(2));
我不太明白为什么根据评论制作临时字符串。
整个问题是char const*
和std::string
是完全不同的数据类型。
为了比较:
class A { };
class B { };
void f(A a);
void g()
{
B b;
f(b); // does not work...
}
我很确定你已经遇到过了。
现在让我们更改类 A:
class A
{
public:
A() { } // default constructor
A(B b) { } // accepting an instance of B
};
现在,您可以执行以下操作:
B b;
f(A(b)); // create a TEMPORARY A from B; you need it, as f ONLY accepts an A!
f(b); // again, create a temporary just as before - this time IMPLICITLY
您可以通过显式构造函数来禁止从 B 隐式创建 A:
class A
{
public:
A() { }
explicit A(B b) { } // now A cannot be created implicitly any more
};
B b;
//f(b); // now is not accepted by compiler any more
f(A(b)); // this still works, of course
与std::string
完全相同:它有一个接受char const*
的非显式构造函数...
相关文章:
- 康斯特指针C++斯特劳斯特鲁普
- C++:根据斯特劳斯特鲁普的例子播种随机数
- C++:斯特劳斯特鲁普iterator_traits示例不编译?
- packaged_task示例问题?斯特劳斯特鲁普示例修改
- C++ 斯特劳斯特鲁普的"std_lib_facilities.h"字符串结构 – 警告:无符号表达式的比较
- 为什么当作为常量字符* 返回时会在此处创建临时字符串?[斯特劳斯特鲁普的书例]
- 如何使用埃拉托斯特内斯筛算法改进素数程序
- 斯特劳斯特鲁普 第四章 练习 11.
- 斯特劳斯特鲁普 第 4 章 练习 6:提高效率
- 斯特劳斯特鲁普在函数中传递参数的准则
- 第4章 斯特劳斯特鲁普钻头一个具有挑战性的一步(至少对我来说!
- 斯特劳斯特鲁普使用C++的购买力平价:第7章,第7节("Recovering from errors")
- 如何做真正的斯特图尔?不会引入实际字符串
- 斯特劳斯特鲁普的"Simple_window"在按下按钮时收缩"Next"
- 我相信斯特劳斯图普的书,第三版第368页有一个错别字。有人可以确认吗?
- 为什么奥斯特林斯tream没有清空
- 模板 :: 斯特劳斯特鲁普的例子没有编译
- 在斯特劳斯特鲁普的PPP2e第7章钻头中找不到第三个错误
- 斯特劳斯特鲁普的P:PP 第4章 钻头:卡住
- 斯特劳斯特鲁普的C++书练习