• Create Account

### #ActualKing Mir

Posted 05 February 2013 - 10:57 PM

However, I (think) I still don't understand the uses of the copy ctor/assignment op;

class Foo{
private:
int data
public:
/*normal ctor*/
Foo(int d) : data(d) {};
/*copy ctor*/
Foo(const &Foo copy) : data(copy.data){};
/*assignment op*/
Foo& operator=(const &Foo copy){ data = copy.data };
};



is the above correct?

It's bad style, because the default copy constructor and assignment operator do the same thing. Typically the reason you need to overload these functions is when you are writing a class that manages a resource, or is a container.

Also, for managing resources, you can sometimes avoid writing the rule of three functions, by useing a smart pointer, like unique_ptr with a custom deleter.

### #2King Mir

Posted 05 February 2013 - 10:49 PM

However, I (think) I still don't understand the uses of the copy ctor/assignment op;

class Foo{
private:
int data
public:
/*normal ctor*/
Foo(int d) : data(d) {};
/*copy ctor*/
Foo(const &Foo copy) : data(copy.data){};
/*assignment op*/
Foo& operator=(const &Foo copy){ data = copy.data };
};



is the above correct?

It's bad style, because the default copy constructor and assignment operator do the same thing. Typically the reason you need to overload these functions is when you are writing a class that manages a resource, or is a container.

### #1King Mir

Posted 05 February 2013 - 10:47 PM

However, I (think) I still don't understand the uses of the copy ctor/assignment op;

class Foo{
private:
int data
public:
/*normal ctor*/
Foo(int d) : data(d) {};
/*copy ctor*/
Foo(const &Foo copy) : data(copy.data){};
/*assignment op*/
Foo& operator=(const &Foo copy){ data = copy.data };
};



is the above correct?

It's bad style, because the default copy constructor and assignment operator do the same thing. Typically the reason you need to overload these functions is when you are writing a class that manages a resource, or is a container.

if so, what do they have to do with dynamically allocated memory?

Hodgeman's example shows how a dynamic array would use the rule of three. It illistrated the use well but: DON'T USE IT. If you need a dymic array, use std::vector.

Also, often instead of writing the rule of three functions, you can often just use a unique_ptr (or other smart pointer) around the guts of your resource, and write a custom deleter.

PARTNERS