Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a copy constructor with instance being created

Tags:

c++

visual-c++

I am not asking about the logic of such a call, rather I'm interested in a difference of support b/w Visual C++ and GCC / Clang. Visual C++ will not allow a new instance of an object to be used as the parameter for its own copy constructor. GCC and Clang allow this. Considering that 'int i = i;' is allowed, I'm wondering whether Visual C++ has a bug.

class test {
private:
    test() {}
public:
    test(const test& t) {}
};

int main(void) {
    int i = i;
    test t(t); -- this line gives an error in Visual C++
    return 0;
}
like image 844
nachum Avatar asked Apr 26 '26 01:04

nachum


1 Answers

To quote the C++ standard (3.3.2):

The point of declaration for a name is immediately after its complete declarator and before its initializer

In your first statement, the declarator ends after int i, and so the name i is available where it's used in the initializer (= i), so the statement is well-formed, but its behaviour is not defined.

In your second statement, the declarator ends after test t(t), and there is no initializer; the name t is not available where you use it, so the statement is ill-formed.

So the compiler is behaving correctly. I would hope it could be configured to give a warning about the first statement, but it's not required to reject it; it is required to reject the second, as you say it does.

like image 194
Mike Seymour Avatar answered Apr 28 '26 15:04

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!