包含指针的类的向量

huangapple go评论57阅读模式
英文:

Vector holding a class which holds a pointers

问题

I have a template class Position which has a pointer to an Entry object. Can it create errors if I am creating my Positions on the stack, and then inserting them in the std::vector?

Here is my Position Template:

template <typename K, typename V>
class Position
{
private:
    Entry<K, V> *ptr;
    int index;
public:
    Position(Entry<K, V> &e, int index){
        *ptr = e;
        this->index = index;
    }

And I am inserting like this in the vector:

Entry<int, int> e(20, 20);
//Creates Position with reference to Entry and Index as value.
storage.push_back(Position<K, V>(e, 10));

I am not fully sure how memory would work for a simple insertion, even more if I am inserting inside a local function, and the Position is created locally.

So, can I do it, should I use new so it stays on the Heap? Am I doing things wrong?
Thanks for the help in advance.

英文:

I have a template class Position which has a pointer to an Entry object. Can it creates errors if I am creating my Positions on the stack, and then inserting them in the std::vector?

Here is my Position Template:

template &lt;typename K, typename V&gt;
class Position
{
private:
    Entry&lt;K, V&gt; *ptr;
    int index;
public:
    Position(Entry&lt;K,V&gt; &amp;e, int index){
        *ptr = e;
        this-&gt;index = index;
    }

And I am inserting like this in the vector:

Entry&lt;int, int&gt; e(20, 20);
//Creates Position with reference to Entry and Index as value.
storage.push_back(Position&lt;K,V&gt; p(e, 10));

I am not fully sure how would memory work for a simple insertion. Even more if I am inserting inside a local function, and the Position is created locally.

So, can I do it, should I use new so it stays on the Heap? Am I doing things wrong?
Thanks for the help in advance.

答案1

得分: 1

我将按不同层次回答你的问题:1) 清理你发布的代码,因为它不是你所想的那样运行的,2) 处理你对存储超出范围的对象指针的直觉,3) 讨论一些不使用指针的备选设计选项。

Posted Code

考虑一下 Position 构造函数。第一个参数是对 Entry 的引用。表达式 *ptr = e 复制了由 e 引用的对象,并将其存储在由 ptr 指向的位置,该位置未初始化,可能指向任何地方,显然是一个错误。根据你口头解释,我认为表达式应该是 ptr = &e,将 e 的地址存储在 ptr 中。

Storing Pointers

你的直觉是正确的,存储指向超出范围的对象的指针肯定会失败。正如你提到的,一种选择是在堆上分配对象并存储指向该对象的指针,这将在你从堆中删除对象之前保持有效。尽管如此,我建议不要使用裸指针。

Design Options

我不了解你的整体代码,所以你可能需要根据你的情况来调整这些策略。

  1. 直接在 Position 中存储 Entry 对象。假设这仍然满足你的代码的其他要求,即 Entry 不会在 Position 对象外部以某种方式共享或更改。

  2. 使用 new 分配 Entry 对象,但将结果存储在智能指针中,如 std::unique_ptr(或 std::shared_ptr 如果你需要多个引用)。智能指针可以像值一样传递并存储在对象中,类似于 int。我无法强调这比使用裸指针要好多少。

Asking Questions

当你发布问题时,将足够的代码以复制你遇到的问题非常有帮助。该代码应该可以编译(除非问题与编译错误有关)并运行。

这有多个好处。对于提问者来说,通常构建一个最小的可重现示例的过程会指导他们朝着正确的方向前进。它还将问题转化为问题的可靠规范。对于回答者来说,这使得更容易处理问题。

英文:

I am going to address you question at a few different levels: 1) cleanup the code you posted because it is not doing what you think it is, 2) address your intuition about storing a pointer to an object that goes out of scope, and 3) walk through some alternate design options that don't use pointers.

Posted Code

Consider the Position constructor. The first argument is a reference to an Entry. The expression *ptr = e copies the object referenced by e and stores it in the location pointed to by ptr which is uninitialized and could point anywhere, clearly a bug. Based on your verbal explanation, I think the expression should have been ptr = &amp;e, which stores the address of e in ptr.

Storing Pointers

You intuition is correct that storing a pointer to an object that goes out of scope will certainly fail. As you mention, one option is to allocate the object on the heap and store that pointer which will remain valid until you delete the object from the heap. That said, I recommend not working with raw with pointers.

Design Options

I don't know your overall code, so you may have to adapt these strategies to your situation.

  1. Store the Entry object directly in the Position. This is clearly the easiest solution assuming it still meets the other requirements of your code, i.e. the Entry's are not somehow shared or changed outside of the Position object.

  2. Allocate the Entry object using new but store the result in a smart pointer like std::unique_ptr (or stud::shared_ptr if you need multiple references to it). The smart pointer can be passed around and stored in objects by value similar to an int. I can't overstate how much better this is than working with raw pointers.

Asking Questions

When you post a question, it is really helpful to post enough code to replicate the problem you are experiencing. The code should compile (unless the question is about a compilation error) and run.

This had multiple benefits. For the questioner, often to process of constructing a minimal, reproducible example points them in the right direction. It also turns the question into a reliable specification of the issue. For the answerers, it makes it a lot easier to work on the problem.

huangapple
  • 本文由 发表于 2023年5月11日 08:08:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223319.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定