Does copy occur if variable not defined as a reference?


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Does copy occur if variable not defined as a reference?

  1. #1
    Join Date
    Apr 2005
    Posts
    2

    Question Does copy occur if variable not defined as a reference?

    I'm sure this has been asked before in this forum, but what I need is confirmation on this: If a variable that is assigned a reference to some struct is defined without the &, i.e.

    Some_Type_t some_type = some_object.getSomeType();

    instead of

    Some_Type_t& some_type = some_object.getSomeType();

    where method getSomeType() returns a reference to Some_Type_t, will some_type be a reference to the the Some_Type_t object or will it be a copy of the object?

    I've looked in many books and places online but can't seem to find the answer. Thanks.

  2. #2
    Join Date
    Nov 2003
    Posts
    4,118
    Quote Originally Posted by seeLTrun
    I'm sure this has been asked before in this forum, but what I need is confirmation on this: If a variable that is assigned a reference to some struct is defined without the &, i.e.

    Some_Type_t some_type = some_object.getSomeType();

    instead of

    Some_Type_t& some_type = some_object.getSomeType();

    where method getSomeType() returns a reference to Some_Type_t, will some_type be a reference to the the Some_Type_t object or will it be a copy of the object?
    It will be a copy, not a reference. This means that any change that you apply to some_type after its initialization will not affect any other object.
    If however some_type was declared as a reference variable:

    Some_Type_t& some_type = some_object.getSomeType();

    some_type would indeed be an alias of another object, so chaging it would affect the actual object to which it is bound.
    C++ is rather explicit (unlike Java for instance) in this respect: when you want a reference or a pointer, you must use & and * , respectively in the declaration of a variable. Otherwise, the result is an independent object.
    Danny Kalev

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center