copy ctor semantics

Discussion in 'C++' started by puzzlecracker, Apr 20, 2008.

  1. Why should the copy constructor take a const reference and not just a
    const?

    If efficiency is no longer an issue, say size of the object won't
    noticeably degrade performance, is it because we can assign temp
    object only to const reference, and not just const?


    class string {
    public;
    string();
    operator char *();
    string (const string & )

    };


    Say, we have string s="hello";

    wouldn't that work if copy ctor took const?

    I just don't see any reasons other than efficiency.

    Thanks
     
    puzzlecracker, Apr 20, 2008
    #1
    1. Advertising

  2. On Sun, 20 Apr 2008 18:43:54 +0200, puzzlecracker <>
    wrote:

    > Why should the copy constructor take a const reference and not just a
    > const?
    >
    > If efficiency is no longer an issue, say size of the object won't
    > noticeably degrade performance, is it because we can assign temp
    > object only to const reference, and not just const?
    >
    >
    > class string {
    > public;
    > string();
    > operator char *();
    > string (const string & )
    >
    > };
    >
    >
    > Say, we have string s="hello";
    >
    > wouldn't that work if copy ctor took const?
    >
    > I just don't see any reasons other than efficiency.
    >
    > Thanks



    Why copy ctor should be allowed to change the element passed at him ?
     
    David Côme, Apr 20, 2008
    #2
    1. Advertising

  3. puzzlecracker

    Kai-Uwe Bux Guest

    puzzlecracker wrote:

    > Why should the copy constructor take a const reference and not just a
    > const?

    [snip]

    Given a function with signature

    maybe_void foo ( A const a );

    calling foo(a) will call the copy constructor to create a temporary of of
    the parameter for the function to work on. The function will not be allowed
    to modify the temporary.

    Therefore, foo(a) invokes the copy constructor for A.

    Question: what happens if you had a copy constructor with signature:

    A ( A const a );


    Best

    Kai-Uwe Bux
     
    Kai-Uwe Bux, Apr 20, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Apricot
    Replies:
    4
    Views:
    530
    velthuijsen
    Apr 16, 2004
  2. NVH
    Replies:
    8
    Views:
    489
    mlimber
    Jul 6, 2006
  3. Grizlyk
    Replies:
    8
    Views:
    489
    Grizlyk
    Nov 29, 2006
  4. , India

    copy ctor vs default ctor

    , India, Aug 15, 2007, in forum: C++
    Replies:
    2
    Views:
    412
    =?ISO-8859-1?Q?Erik_Wikstr=F6m?=
    Aug 15, 2007
  5. puzzlecracker
    Replies:
    8
    Views:
    431
    James Kanze
    Apr 15, 2008
Loading...

Share This Page