View Single Post
Join Date: Jul 2006
Posts: 1,091
Reputation: MattEvans is a jewel in the rough MattEvans is a jewel in the rough MattEvans is a jewel in the rough 
Solved Threads: 63
Moderator
Featured Poster
MattEvans's Avatar
MattEvans MattEvans is offline Offline
Veteran Poster

default arguments in copy constructor

 
0
  #1
Dec 3rd, 2008
If I add default arguments to the end of my copy constructor, is it still considered a copy constructor? E.g. will it still be used in the places where a copy constructor would normally be used (or automatically generated).

I can verify that it works on one compiler (g++). That is, this does output the "copy ctor" message 3 times:

  1. #include <iostream>
  2.  
  3. class Context
  4. {
  5. // real thing actually has some methods
  6. };
  7.  
  8. class A
  9. {
  10. private:
  11. Context & m_context;
  12.  
  13. public:
  14. A ( Context * context )
  15. :m_context ( MATT_DEREF ( context ) )
  16. {
  17. // probably do something with context here..
  18. }
  19.  
  20. A ( const A & a, Context * new_context = 0 )
  21. :m_context ( new_context ? *new_context : a.m_context )
  22. {
  23. std::cout << "copy ctor\n";
  24. // probably do something with context here..
  25. }
  26. };
  27.  
  28. void test ( A a )
  29. { return; }
  30.  
  31. int main ( void )
  32. {
  33. Context c1, c2;
  34. A a1 ( &c1 );
  35. // implictly copying by passing as value
  36. test ( a1 );
  37. // explicitly copying in the same context
  38. A a2 ( a1 );
  39. // copying to a new context
  40. A a3 ( a1, &c2 );
  41. return EXIT_SUCCESS;
  42. }

But, will this always work O.K.? are there any caveats/pitfalls etc?

Other alternatives considered:

- I can't have the generated copy ctor used, for various reasons (e.g. other pointers/reference members shouldn't be shallow copied ).
- I don't want to pass the pointer to "context" in later, because that makes other areas unpleasant. E.g. I need to use "context" in the constructor, and it's not meant to be trivially reseatable.
- I do want the rest of the copy constructors features (i.e. being able to initialize the object & its bases in order).
- I'd rather not have to write 3 constructors for every class like this.
Last edited by MattEvans; Dec 3rd, 2008 at 2:53 pm.
Plato forgot the nullahedron..
Reply With Quote