Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

C++ default behavior for arrays - shallow copies?

As the title says - I need the content of the v array not to change outside of the function.

I thought that it would not happen (because AFAIK the default behavior of arrays is to deep copy - but it looks like it is not).

#include <iostream>

using namespace std;

void testModif(int *v)
{
    for (int i = 0; i < 5; i++)
    {
        v[i]++;
    }
}

int main()
{
    int *v;
    v = new int[100];
    *v = 0;
    testModif(v);
    for (int i = 0; i < 5; i++)
    {
        cout << v[i] << " ";
    }
}

How can I make v not change after running testModif?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First you can enlist the compilers help by declaring as

void testModif(const int *v);

I.e. as v being a non-const pointer to const int. I.e. you can e.g. increment the copy of the pointer, but not change what the pointer points to.

With that change the shown code will get errors/warnings, which at least tell you that you are doing what you do not want to do.

Then you need to change your code to follow your self-decided rule.
For the shown code that would require making a copy of the array itself (not only of the pointer pointing to it). Exactly, that would match "deep copy" in contrast to the "shallow copy" you mention.

Most closely to your shown code would be a local copy, an array of size 5 (magic number, but you know what I mean) or something malloced of proper size (and of course freed before leaving the function).

Obviously making a local copy, incrementing all members and then leaving the function again normally would seem pointless. I trust that this is purely to be blamed to you making an appropriate MRE. I.e. the point that intentionally not changing the original values and only locally incrementing is what you want to achieve.

Of course I am not contradicting the comments to your question, which recommend the more C++ way of doing things, with standard containers, like std::array, std::vector.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...