double assignment

T

Triple-DES

Consider the following code:

struct C {
C(int i) : j(i) {}
int j;
};

int main() {
C c1(42);
C c = c = c1;
}

Does it have well-defined behaviour?

DP
 
T

Triple-DES

I think it is not a double assignment. It is initialization and assignment..
C c = c = c1; can be rewritten as C c (c = c1),
which makes clear that c is used as a parameter for its own construction.

Yes, a more suitable topic would be: copy-initialization and
assignment. It seems obvious that C c = c; is undefined. However I am
still not convinced about C c = (c = c1).

DP
 
P

Pascal J. Bourguignon

Triple-DES said:
Consider the following code:

struct C {
C(int i) : j(i) {}
int j;
};

int main() {
C c1(42);
C c = c = c1;
}

Does it have well-defined behaviour?

AFAIK, in your specific case, yes. However, the copy constructor
(implicit in this case) may be called as many times as you assign to
c. So if you had your own copy constructor, you would have to be
careful about side effects and order of member copying, etc.
 
J

James Kanze

Consider the following code:
struct C {
C(int i) : j(i) {}
int j;
};
int main() {
C c1(42);
C c = c = c1;
}
Does it have well-defined behaviour?

Formally, I don't think so, since you're calling C::eek:perator=
before having constructed C (and the constructor is not
trivial).

In practice, I don't think it matters, since I don't think you'd
ever want to do this anyway.
 
D

Daniel Pitts

Triple-DES said:
Consider the following code:

struct C {
C(int i) : j(i) {}
int j;
};

int main() {
C c1(42);
C c = c = c1;
}

Does it have well-defined behaviour?

DP
The real question is,
WHY!?!!?
It seems likely to be a programmer error, and the meaning is very much
*not* intuitive. If you have to spend that much time worrying about
whether its well-defined, and what its defined behavior is, then you
should consider a different idiom that is more intuitive for human readers.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top