copy constructor in MSVC

This is a discussion on copy constructor in MSVC within the C++ Programming forums, part of the General Programming Boards category; I noticed that when you add an object to a vector in MSVC 2005 the copy constructor of that objects ...

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    330

    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
    Location
    Singapore
    Posts
    22,274
    It might be easier to understand if you posted the appropriate code snippets. Also, note that copy construction can be elided.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

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

    Code:
    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:

    Code:
    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, 03:41 PM
  2. calling copy constructor from template
    By Ancient Dragon in forum C++ Programming
    Replies: 3
    Last Post: 09-28-2005, 02:54 PM
  3. dynamic memory alloccation & returning objects
    By haditya in forum C++ Programming
    Replies: 8
    Last Post: 04-22-2005, 12:55 AM
  4. Copy constructors and operator=()
    By filler_bunny in forum C++ Programming
    Replies: 13
    Last Post: 08-25-2003, 08:43 AM
  5. Copy Constructor Help
    By Jubba in forum C++ Programming
    Replies: 2
    Last Post: 11-07-2001, 11:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21