开发者

Disadvantage of Copy Constructor [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago. 开发者_如何学编程

why we use copy constructor? what are the benefits and disadvantages of copy constructor?


The "disadvantage" is that for non-copyable types, we have to forbid copying explicitly:

class Foo
{
    // ...

private:

    Foo(const Foo&);
    Foo& operator=(const Foo&);
}


The only disadvantage I can think of to a copy constructor is that some large objects can be expensive to copy (eg. copying a long string involves allocating a large block of memory then copying all the content). C++0x solves this to some extent using move constructors which allow the content of one object to be moved in to another, which is usually a cheap operation.


I was just reading about this. I'm pretty sure this is also correct, along with the other answers. Note this applies just the same for assignment.

If you do not specify a copy constructor for an object you've created, then try to copy it, the compiler may create a copy constructor that is inappropriate for your object.

Say you have a class with a member that is a pointer and you haven't specified a copy constructor. If the compiler decides to simply make an exact duplicate of the object, the pointer will also point to the same memory as the original object, causing you all sorts of trouble when the memory is released for that pointer by one object, but it is still in use by another.

EDIT: Updated this to reflect what sbi has said. I presume the rest is correct.


We use a custom copy-constructor so that we can copy our objects. Many objects can be copied by simply copying their data members, and can hence rely on the default copy-constructor generated by the compiler, but sometimes this doesn't adequately capture the need. For instance, an object might have some data members that point to other data members in the same object. Simply copying such a pointer to the target object will leave the data member in the target pointing back to a data member in the source object.

For example:

class FastString {
public:
    ...
    FastString(const FastString& s) : len_(s.len_) {
        start_ = len_ > 8 ? new char[len_] : &insitu_;
        memcpy(start_, s.start_, len);
    }
    ...

private:
    char *start_;
    size_t len_;
    char insitu_[8];
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜