Bug in precedence for built-in types?

G

Guest

I would expect the output to be:

5
post increment
assign
5

This is the case for Visual c++ 6 AND g++ 3.4.2. However, for visual c++
7.1, I get:

6
post increment
assign
5

Any ideas? Is this undefined behaviour? I think its pretty well defined. But
in either case, its inconsistent for v7.1 between built-ins and udt's!

#include <cassert>
#include <iostream>

struct test
{
int me;
test(int mee):me(mee){}
test operator++(int)
{
test a(*this);
++me;
std::cout << "post increment" << std::endl;
return a;
}

operator int(){return me;}

test & operator=(const test & rhs)
{
if(&rhs!=this) std::cout << "assign" << std::endl;
this->me = rhs.me;
return *this;
}
};

template<typename T>
void doit()
{
T aaa(T(5));
aaa = aaa++;
std::cout << int(aaa) << std::endl;
}

int main()
{
doit<char *>();
doit<test>();
}
 
N

Norman Diamond

For the built-in type it isn't calling your post-increment function. With a
function call there would be some sequence points associated with the
function call, but without a function call those sequence points do not
exist. Without those sequence points, you got off lucky. This line of
code:
aaa = aaa++;
is allowed to format your hard drive.
 
C

Carl Daniel [VC++ MVP]

Norman said:
For the built-in type it isn't calling your post-increment function. With
a function call there would be some sequence points associated
with the function call, but without a function call those sequence
points do not exist. Without those sequence points, you got off
lucky. This line of code:
aaa = aaa++;
is allowed to format your hard drive.

To expand on that a little bit -

aaa = aaa++;

attempts to modify a variable twice between sequences points if the typeof
aaa is a built-in type but not if it's a class type.

See this recent thread

http://groups.google.com/group/micr...192f5ef7f60/2f734ae4cab7c23b#2f734ae4cab7c23b

for a lot of discussion as to why this is undefined behavior and what all
that means.

-cd
 

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

Top