std::cout 在打印变量与函数表达式时的行为不同
std::cout behaves differently when printing variable vs function expression
我是 c++ 的新手,我面临着我不理解的std::cout
的奇怪行为。特别是,当我想打印第二个节点的值时,使用cout << nd.next[2]->next[17]->val
,我得到一些复杂的字节。但是,如果我先将其设置为变量,例如string let2 = nd.next[2]->next[17]->val
,然后使用cout << let2
,它会打印正确的字符。我的代码在下面,我正在实现一个尝试。(另外,由于我对c ++非常陌生,因此非常感谢有关我在代码中做错了什么的任何其他评论(
#include <iostream>
#include <set>
#include <iterator>
#include <map>
#include <string>
#include <unordered_map>
using std::set;
using std::cout;
using std::endl;
using std::string;
struct Node {
Node* next[26];
string val;
void insert(string str) {
cout << "insert " << str << endl;
insert(str, 0);
}
void insert(string str, int idx) {
if (idx >= str.length()) {
return;
}
char cur = str[idx];
int curIdx = cur - 'a';
cout << "cur: " << cur << endl;
cout << "cur idx: " << curIdx << endl;
if (!next[curIdx]) {
Node newNode = Node();
newNode.val = cur;
next[curIdx] = &newNode;
}
next[curIdx]->insert(str, idx+1);
}
};
int plus(int a, int b) {
return a+b;
}
int main() {
Node nd = Node();
nd.insert("cryptography");
string let1 = nd.next[2]->val;
string let2 = nd.next[2]->next[17]->val;
cout << "first letter " << let1 << endl; // c
cout << "second letter " << nd.next[2]->next[17]->val << endl; // wrong
cout << "second letter " << let2 << endl; // work as expected
cout << "sum " << plus(1,2) << endl; // work as expected
// cout << nd.next[2]->next[17]->val << endl;
return 0;
}
关于问题的第二部分("我做错了什么"(,在insert()
方法中,您在堆栈上创建Node()
对象,并next[curIdx]
分配指向该对象的指针。但是,一旦执行步骤超出定义该对象的范围,该堆栈对象就会自动销毁,因此next[curIdx]
最终指向垃圾(该对象在销毁之前曾经存在的内存(。
不确定下一行是如何工作的,next[curIdx]
此时指向垃圾:next[curIdx]->insert(str, idx+1);
相反,您应该使用new
运算符在堆上分配 Node 对象,例如:
if (!next[curIdx]) {
next[curIdx] = new Node(); // allocated on heap
next[curIdx]->val = cur;
}
但是你应该确保在某个时候解除分配(delete
(它们以避免内存泄漏。节点析构函数可能是一个很好的地方 - 你可以递归地delete
下一个数组中的所有非空节点。
此外,您可以使用智能指针而不是原始指针,当无法再访问对象时,它们会自动删除对象(垃圾收集器在其他语言(如 Java 和 C#(中会自动执行此操作(。
有关堆栈与堆的更多信息:https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/
- C++模板函数中的初始化 - 新的初始值设定项表达式列表被视为复合表达式
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 函数返回的 rvalue 引用(表达式)是 xvalue - 但没有标识?
- 折叠表达式和函数名称查找
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 不是 lambda 函数中的常量表达式
- 保证逻辑 AND 表达式中的函数调用
- 函数调用在常量表达式中必须具有常量值
- Tbb 库:错误:编写自定义类函数而不是 lambda 表达式时,对函数的调用不匹配
- 错误:表达式不能用作函数
- 使用表达式 SFINAE 的函数模板的类外定义
- std::cout 在打印变量与函数表达式时的行为不同
- 构造函数中缺少表达式
- 如何在使用模板的函数调用的大括号表达式中推导多维数组的大小
- C++98 中的常量表达式函数
- gcc 是否将非常量表达式函数的内置视为常量表达式
- 试图理解基本的正则表达式函数在c++
- 错误:','令牌之前的预期主表达式 //函数调用