Prev: compilation error when Base Constructor calling pure virtual method
Next: will taking the address of the first element of a string break COW strings?
From: John Bellone on 11 Jul 2010 05:12 On Jul 11, 10:28 am, Sergey Lukoshkin <sergey....(a)gmail.com> wrote: > Hello, everyone! > > I faced such a problem. Say I got the class: > > class foo > { > public: > foo(); > ~foo(); > > private: > > T* m_ptr; > > }; > > I need to implement copy constructor. So, the common signature for it > is foo( const& other ). I have to take the pointer from another > object, assign it to this->m_ptr and then make other.m_ptr = 0. But > such a solution discards constness of the other object and signature > of copy constructor should be foo( foo& other ). > > Is the approach a correct way to implement the copy constructor for > class with member pointer or not? Loosing constness of argument makes > me hesitating. Thanks. I am never a proponent of toying around with the const-ness of a variable. Is there any reason why you merely cannot have a reset() method which is called outside of the copy constructor? jb -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Kenneth 'Bessarion' Boyd on 12 Jul 2010 17:53
On Jul 11, 9:28 am, Sergey Lukoshkin <sergey....(a)gmail.com> wrote: > Hello, everyone! > > I faced such a problem. Say I got the class: > > class foo > { > public: > foo(); > ~foo(); > > private: > > T* m_ptr; > > }; > > I need to implement copy constructor. > .... > So, the common signature for it > is foo( const& other ). I have to take the pointer from another > object, assign it to this->m_ptr and then make other.m_ptr = 0. But > such a solution discards constness of the other object and signature > of copy constructor should be foo( foo& other ). The behavior specified is, loosely, a move constructor with signature foo( foo& other ), suitable for something mimicking std::auto_ptr . Double-check what the specification really is (as you will automatically fail to implement the above direct self-contradiction), then implement what is actually required. Use foo(foo& other) if and only if this prevents using const-casts. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |