Re: Bitwise copy contructor
On 21 Mrz., 03:08, pfultz2 <pful...@yahoo.com> wrote:
On Mar 20, 3:18 pm, Daniel Kr gler <daniel.krueg...@googlemail.com>
wrote:
On 20 Mrz., 09:26, pfultz2 <pful...@yahoo.com> wrote:
How would I go about writing a bitwise copy constructor for a class? I
would like to call memcpy() before any constructors are called on the
members. I cant seem to find any information on this.
It is not really clear to me, what you
question is - a more specific use-case
would help. Are you asking for the
syntax to realize that? Or are you asking
how you can do that without provoking
undefined behavior (UB)?
The life-time and trivial type rules of
C++ put rather severe restrictions on
class types (I assume your class contains
members of class-type, because otherwise
your remark about constructors doesn't
make sense to me), so simply performing
memcpy on a std::string within or without
a constructor will rather easy lead
to UB land.
What are you going to achieve and why
isn't a normal copy constructor
sufficient?
Greetings from Bremen,
Daniel Kr gler
Well if i call a copy constructor like this:
class foo
{
bar b;
public:
foo(cont foo& rhs)
{
memcpy(this, &rhs, sizeof(foo));
}
};
When it calls the copy constructor the constructor for the fields(such
as bar b) are called first, then memcpy() is called. I want to know
how to call memcpy and not call the constructors for the fields.
This doesn't really answer my question, which
was "what do you want to achieve and why isn't
a normal copy constructor sufficient"?
Why doesn't
class foo {
bar b;
};
do the right thing? If bar has a copy-constructor, foo
has also one, which calls the copy-constructor of bar.
If you want to have a user-defined copy-constructor
(for debugging purposes and other reasons), the following
definition should do the right thing:
class foo {
bar b;
public:
foo(const foo& rhs) : b(rhs) {}
};
It seems that you are thinking in C. That is fine, but
then you should program like in C, which doesn't have
the concepts of constructors and destructors.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]