Megatron
Megatron

Reputation: 2949

Disallow the explicit copy of data members without user defined ctor

I have a question about copy constructors/copying objects.

I have a class that has a few properties that I don't want to be copied.

class Action : public Cloneable<Action>
{
public:
     //Constructors and other methods are ommitted
    std::vector<BattleCharacter*> Users;
    std::vector<ActionTargetTuple> Targets;
protected:
    ActionType Type;
    std::string Name;
    int UID;
 }

I want the Users and Targets vectors NOT to be copied when I make a copy of this type of object. Is there a way to mark them as explicitly not copyable without using a custom copy constructor? If not, and I use a custom copy constructor, will I need to define a custom copy constructor for each class that inherits from this one?

Upvotes: 0

Views: 163

Answers (4)

tvn
tvn

Reputation: 634

I agree with answers above, better to provide copy constructor and assignment operator, but if you do not want to do so for some reason (?), change the type of Users and Targets, as variant, use shared_ptr, it will prevent those members from deep copy, for example:

typedef std::vector<BattleCharacter*> USERS;
typedef std::vector<ActionTargetTuple> TARGET;
....
boost::shared_ptr<USERS> Users;
boost::shared_ptr<TARGET> Target;

Also, now shared_ptr is a part of TR1, so it could be used without boost.

Upvotes: 0

seand
seand

Reputation: 5296

Do you need a copy ctor for something like containers or returning objects? If not you might consider creating another method for doing the copy.

Upvotes: 0

Gustavo Mori
Gustavo Mori

Reputation: 8386

You will need to define the copy constructor, so you can customize what gets copied and what doesn't. Luckily, by doing this, you're telling the compiler not to auto-generate the default copy constructor, yours will take its place. So, no worries about derived classes using the default constructor.

As you work through your solution, consider this design pattern.

Upvotes: 0

holtavolt
holtavolt

Reputation: 4468

The default copy constructor will copy everything, so yes - you will need to implement the copy constructor manually to achieve this. As this replaces the default copy ctor, you will not need to define one for each inherited class (unless you want different behavior).

Upvotes: 4

Related Questions