why vector assignment operator not invoked on const vector& ?

Discussion in 'C++' started by zhou, Sep 2, 2003.

  1. zhou

    zhou Guest

    Hi there,

    I am expecting that the following assignment will invoke assignment operator on vector (since myFunc() returns a const
    vector & type), which makes a copy of the vector returned from myFunc():

    vector<myObj*> anotherVec = myFunc();

    const vector<myObj *>& myFunc()
    vector <myObj *> localVec;

    // add objects into localVec

    return localVec;

    However, my understanding is that assignment operator takes const Object& type. However, the assignment operator on
    vector is not invoked here and therefore vector is not copied. Am I missing anything?


    zhou, Sep 2, 2003
    1. Advertisements

  2. zhou

    Ron Natalie Guest

    It has nothing to do with constness. The above is NOT an assignment, it is initialization.
    The copy-constructor is what is invoked.
    Ron Natalie, Sep 2, 2003
    1. Advertisements

  3. Yep.
    The above is *not* an assignment. It is an initialization, hence the
    copy constructor is called (or not, if it is optimized away by the compiler).
    Karl Heinz Buchegger, Sep 2, 2003
  4. This is initialization, not assignment.
    The copy constructor is supposed to be invoked. However, returning a
    reference to a local object is illegal in C++ It causes undefined
    behavior. That's what's happening in your code.
    Andrey Tarasevich, Sep 2, 2003
  5. It does copy the vector, what else would it do?

    Why do you think it does not copy the vector?

    I think you should post some real.

    John Harrison, Sep 2, 2003
  6. Might have been too hasty with my last post. I think I'll bow out now.

    John Harrison, Sep 2, 2003
  7. zhou

    jeffc Guest

    jeffc, Sep 2, 2003
  8. I don't, since you didn't bother to quote any context.
    A vector's copy constructor does copy. If you have code demonstrating a
    case where it doesn't, post it. Otherwise I have no idea what you are
    talking about.

    Kevin Goodsell, Sep 2, 2003
  9. zhou

    zhou Guest

    Thanks. You are right. The copy consturctor is invoked after the local object is destroyed, thus returning a const &
    does no good: it does invoke copy constructor on an already emptied vector.
    zhou, Sep 2, 2003
  10. It is not that it is "emptied". The storage duration of the local vector
    is already over. The vector doesn't exist anymore. That's why your code
    produces undefined behavior.
    Andrey Tarasevich, Sep 2, 2003
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.