English 中文(简体)
保留一个向量值的副本,然后将其重写
原标题:Keeping a copy of a vector value, which will then be over-written
  • 时间:2012-05-27 16:11:00
  •  标签:
  • c++

我有一些代码,如下所示:

MyClass* a = new MyClass();
vector[0] = *a;

MyClass KeepCopy = vector[0];

//
//
vector gets changed
//
//

return KeepCopy

现在vector去做很多事情,然后被覆盖。但是,我希望在函数末尾返回KeepCopy的值。然而,由于向量[0]没有指向其他东西,我认为我被返回了错误的数据。

编辑3:好的,事情就是这样。KeepCopy被分配给vector[0],然后在代码中我对vector[0]做了一些事情。我原以为KeepCopy仍然指向vector[0]的一个版本,但KeepCopy似乎只包含赋值时的值的副本。

稍后,我将vector分配给另一个vector对象(我一次读取两行文本文件,vector包含一行,另一个vector对象包含第二行)。我如何确保KeepCopy指向原始的vector[0]元素(在我开始解析文本文件中的每一行,重新分配向量之前)?

最佳回答

由于您按值(而不是指针/引用)存储对象,对向量[0]的更改不会反映在KeepCopyMyClassinstances中共享指向同一包含对象的指针

如果是这样的话,你应该实现一个正确的复制构造函数,对原始文件进行深度复制(而不是默认的浅层复制,它只是盲目地复制指针的值)

问题回答

为MyClass实现一个复制构造函数并复制对象。不是指针。

正如你所做的:MyClass KeepCopy=vector[0]会将KeepCopy设置为原始对象的副本(通过其复制构造函数)。此副本与向量没有连接,因此不会受到修改向量的影响。

如果我没理解错的话,您的函数中会发生以下步骤

  1. You do some things with vector[0] that modify it.
  2. You reassign the whole vector.

在步骤1之后但在步骤2之前的向量[0]的状态是您想要返回的。这就是你的代码中应该复制的地方。

MyClass foo()
{
    //
    // some stuff
    //

    MyClass* a = new MyClass();
    vector[0] = *a;

    //
    // vector[0] gets modified
    //

    // you want vector[0] s value here, so this is where you should create the copy
    MyClass KeepCopy = vector[0];


    //
    // Whole vector gets reassigned
    //

    return KeepCopy
}




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签