markzzz
markzzz

Reputation: 47985

Should I always deal with reference returning vector?

Not sure here what's happening:

#include <iostream>
#include <vector>

class Voice
{
public:
    double mValue = 0.0;

    Voice() { }
    Voice(const Voice &copy) {
    }    
};

class VoiceManager
{
public:
    std::vector<Voice> mVoices;

    VoiceManager() {
        mVoices = std::vector<Voice>(numVoices, Voice());   

        for (int i = 0; i < numVoices; i++) {
            mVoices[i].mValue = 100.0;
        }        
    }

private:
    int numVoices = 16;    
};

int main()
{    
    VoiceManager voiceManager;
    Voice voice = voiceManager.mVoices[2];
    std::cout << voice.mValue << std::endl;
}

I set mValue for each Voice with value 100 with operator [], but when I try to retrieve the object with the same [] operator, it seems it returns not that element? It prints 0.

Instead, if I do:

Voice &voice = voiceManager.mVoices[2];

I can finally see the updated value.

What's happening here?

Upvotes: 0

Views: 75

Answers (1)

TemplateRex
TemplateRex

Reputation: 70536

As indicated in the comments, your copy constructor is a) wrong and b) superfluous

class Voice
{
public:
    double mValue = 0.0;

    // don't provide default constructor, unless you have another constructor
    // use compiler-generated copy-constructor
};

class VoiceManager
{
    int numVoices = 16;    // move up here so that member-initialization works
public:
    std::vector<Voice> mVoices;

    VoiceManager() 
    :
        mVoices(numVoices) // member-initialize
    {
        for (int i = 0; i < numVoices; i++) {
            mVoices[i].mValue = 100.0;
        }        
    }
};

int main()
{    
    VoiceManager voiceManager;
    Voice voice = voiceManager.mVoices[2];
    std::cout << voice.mValue << std::endl;
}

Live Example

Note that I also did a minor cleanup on the constructor for VoiceManager, by using member-initialization syntax.

As for the other question: the initialization

Voice voice = voicemanager.mVoice[2]; 

actually calls your copy constructor

Voice(voicemanager.mVoice[2]);

(the = sign here does not imply assignment!)

Upvotes: 2

Related Questions