dimanche 27 novembre 2016

C++ Order of Evaluation

I'm trying to figure out if there's any specification in the C++11 standard re. expected behavior for the following code (GitHub link here):

struct Scalar {
    int data;

    Scalar(int x) : data(x) {}

    int get() {
        return data;
    }

    Scalar &square() {
        scale(data);
        return *this;
    }

    void scale(int rhs) {
        data *= rhs;
    }
};

int main() {
    Scalar v(3);

    v.square().scale(v.get());

    return v.data;
}

This comes up mostly because of the discovery that this does different things between g++ and clang++:

$ g++ --version
g++ (GCC) 6.2.1 20160830
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ clang++ --version
clang version 3.9.0 (tags/RELEASE_390/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

$ g++ -std=c++11 order_of_ops.cpp -o a.out && ./a.out; echo $?
27

$ clang++ -std=c++11 order_of_ops.cpp -o a.out && ./a.out; echo $?
81

Aucun commentaire:

Enregistrer un commentaire