Thread: copy constructor in MSVC

  1. #1
    Registered User
    Join Date
    Jan 2007

    copy constructor in MSVC

    I noticed that when you add an object to a vector in MSVC 2005 the copy constructor of that objects is called twice. There is a new temporary created inside the vector::insert code with the comment "// in case _Val is in sequence"

    In gcc it is only called once.

    Anyone know why the MSVC implementation does this? I dont get the comment next to it.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    It might be easier to understand if you posted the appropriate code snippets. Also, note that copy construction can be elided.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    The larch
    Join Date
    May 2006
    This would avoid situations such as

    vec.insert(vec.end(), vec[0]);
    vec[0] is a reference into the same vector. Now imagine that the buffer needs to be resized. If the implementation is not careful, it might end up using a reference to the object it has just moved to a different place.

    Or another problem:

    vec.insert(vec.begin(), vec.back());
    Even if the vector didn't reallocate the memory, if it started by making room for the new item, vec.back() might end up referencing the last but one item before it is inserted.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Gcc can't find obvious copy constructor
    By SevenThunders in forum C++ Programming
    Replies: 13
    Last Post: 03-19-2009, 02:41 PM
  2. calling copy constructor from template
    By Ancient Dragon in forum C++ Programming
    Replies: 3
    Last Post: 09-28-2005, 01:54 PM
  3. dynamic memory alloccation & returning objects
    By haditya in forum C++ Programming
    Replies: 8
    Last Post: 04-21-2005, 11:55 PM
  4. Copy constructors and operator=()
    By filler_bunny in forum C++ Programming
    Replies: 13
    Last Post: 08-25-2003, 07:43 AM
  5. Copy Constructor Help
    By Jubba in forum C++ Programming
    Replies: 2
    Last Post: 11-07-2001, 11:15 AM