将非动态分配的对象推向指针的向量

发布于 2025-02-10 03:50:08 字数 412 浏览 2 评论 0原文

我一直在尝试在代码屏幕上编码但没有任何运气时弄清楚这个问题。

因此,基本上,我在函数中具有以下代码:

Node * newNode;
newNode->data = num;
//root is defined somwhere at the top as 'Node * root';
root->adj.push_back(newNode);

以及以下结构:

struct Node{
    int data;
    vector<Node*> adj;
};

当我对向量进行推动_back时,程序只需循环2-3秒,然后以非零退出代码退出。如果我动态分配内存,它似乎可以正常工作。当指针没有指向特定的内存块时,该程序会以某种方式爆炸吗?

I've been trying to figure out this issue while I was coding on Codeblocks but didn't have any luck.

So basically I have the following code inside a function:

Node * newNode;
newNode->data = num;
//root is defined somwhere at the top as 'Node * root';
root->adj.push_back(newNode);

and the following struct:

struct Node{
    int data;
    vector<Node*> adj;
};

When I do the push_back to the vector the program just cycles for 2-3 seconds and exits with a non-zero exit code. If I allocate the memory dynamically It seems to work correctly. Does the program somehow blow up when the pointer is not pointing to a specific block of memory?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迟到的我 2025-02-17 03:50:08

C ++中未指向对象的“遍历”指针是未定义的行为。

指针不必指向动态分配的对象,但这是典型的。指针可以指向自动存储对象。例如:

Node bob;
Node* root = &bob;

但是,在每种情况下,您都负责管理这些对象的寿命。自动存储对象生存,直到当前范围结束,临时对象,直到当前完整表达式结束,并动态分配的对象为delete d。

智能指针可以帮助解决终生管理问题,但它们只能有所帮助。他们无法解决它,您仍然必须意识到一生。

许多C ++语言都有自动垃圾收集,这使得终身少了程序员的问题。您在C ++方面没有任何帮助。

"Traversing" pointers that are not pointing at objects is undefined behavior in C++.

The pointer doesn't have to point at a dynamically allocated object, but that is typical. The pointer could point at an automatic storage object. For example:

Node bob;
Node* root = &bob;

however, in every case, you are responsible for managing lifetime of these objects. Automatic storage objects survive until the end of the current scope, temporary objects until the end of the current full expression, and dynamically allocated objects until they are deleted.

Smart pointers can help a bit with lifetime management issues, but they only help. They do not solve it, and you still have to be aware of lifetime.

Many post-C++ languages have automatic garbage collection that makes lifetime less of the programmers problem. You do not have this help in C++.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文