Thread: Argument passing vs copy initialization

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    144

    Argument passing vs copy initialization

    Hi. On page 4 of "A Tour of C++", Bjarne Stroustrup writes:

    The semantics of argument passing are identical to the semantics of copy initialization.
    I'm not sure that I fully understand this. Is there some example code that will demonstrate this? Is it possible to "trap" any copy initialization that occurs in argument passing?

    Richard

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    You'll need to provide more content, not everyone will have access to that book.

    The following demonstrates this to some extent:

    Code:
    int by_value(std::string test);
    When this function is called a copy of test will be made by calling the std::string copy constructor. Remember, by default parameters are passed by value. To avoid the copy you can pass the parameter by reference/const reference.

    Is it possible to "trap" any copy initialization that occurs in argument passing?
    What do you mean by "trap"? For non-standard classes you can create your own copy constructor to illustrate or possibly "trap" this behavior.

  3. #3
    Registered User
    Join Date
    Feb 2011
    Posts
    144
    What about this?

    Code:
    #include <iostream>
    
    class Foo {
      public:
        Foo()      : x {}  {}
        Foo(int n) : x {n} {}
        Foo(const Foo& rhs) {
          std::cout << "Copy constructor" << std::endl;
          x = rhs.x;
        }
      private:
        int x;
    };
    
    void fn(Foo f) {
    }
    
    int main() {
      Foo f;
      fn(f);
    }
    Overloading the assignment operator as well does not change what the program prints.

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    When arguments are passed by value, the copy constructor is invoked. If you want to "trap" anything it would be in there. Assignment is never involved. unless for some reason the copy constructor is written in terms of it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing a pointer as an argument
    By effup in forum C Programming
    Replies: 14
    Last Post: 03-27-2015, 01:22 PM
  2. passing pointer argument
    By timhxf in forum C Programming
    Replies: 8
    Last Post: 01-08-2007, 10:38 AM
  3. Argument passing
    By Tarper67 in forum C++ Programming
    Replies: 1
    Last Post: 06-13-2003, 02:59 PM
  4. ADT Initialization/Passing of Array from Friended ADT
    By Wiggin in forum C++ Programming
    Replies: 1
    Last Post: 04-27-2002, 12:45 AM
  5. argument passing
    By theweirdo in forum C Programming
    Replies: 1
    Last Post: 01-29-2002, 07:42 PM

Tags for this Thread