does this implement a copy constructor correctly

i am working on copy constructors now and just wanted to see if i correctly did this. a temporary scope is introduced to make one of the pointers go bad. if im not testing this right please let me know. im temporarily editing out the copy constructor to see the different results.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::cin;

class stickfigure
{
public:
    stickfigure(int j)
    {

        test = new int(j);

    }
    stickfigure(const stickfigure& ref)
    {
        test = new int;
        *test = *ref.test;
    }
    virtual ~stickfigure()
    {
        delete test;
    }

    void print() const{cout << *test << endl;}

private:

    int* test;
};

int main(int argc, char** argv)
{
    stickfigure stickone(88);
    stickone.print();

    {

        stickfigure sticktwo(stickone);
        sticktwo.print();
    }

    stickone.print();
}

Last edited on
a temporary scope is introduced to make one of the pointers go bad.


That scope only affects sticktwo

The copy constructor is ok - although you could have done it in one go:
1
2
3
4
5
    stickfigure(const stickfigure& ref)
    {
        test = new int(*ref.test);
        //*test = *ref.test;
    }
You can simplify this a bit (and make it more efficient) by using member initialization lists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class stickfigure
{
public:
    stickfigure(int j)
    : test(new int(j))
    {}

    stickfigure(const stickfigure& ref)
    : test(new int(*ref.test))
    {}

    virtual ~stickfigure()
    {
        delete test;
    }

    void print() const{cout << *test << endl;}

private:

    int* test;
};


This is a bit more advanced, but a safer way to do this is to use a smart pointer such as boost::scoped_ptr:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class stickfigure
{
public:
    stickfigure(int j)
    : test(new int(j))
    {}

    stickfigure(const stickfigure& ref)
    : test(new int(*ref.test))
    {}

    void print() const{cout << *test << endl;}

private:

    boost::scoped_ptr<int> test;
};


Note that there is no need for a destructor now. The scoped_ptr will automatically release the memory. This also prevents the class from being accidentally copied, thus preventing the memory management problems, if a copy constructor is not defined. This is because scoped_ptr is not copyable.

http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/scoped_ptr.htm
Interesting thanks guestgulkan and pangalactic. thats kind of neat. I just got boost working with codeblocks too yesterday.
Last edited on
Topic archived. No new replies allowed.