QIANYL
QIANYL

Reputation: 41

Why default copy constructor can receive undefined static member variable?

Here is my code:

#include <iostream>

class Foo {
public:
    Foo() { std::cout << "Constructed" << std::endl; }
    // Comment 1.
    // Foo(const Foo& f) { std::cout << "Copy constructed." << std::endl; }
    void Miao() { std::cout << "Miao" << std::endl; }
};

class Bar {
public:
    static Foo f;
};

// Comment 2.
// Foo Bar::f;
Foo x(Bar::f);

int main() {
    x.Miao();
    return 0;
}

The result is:

Miao

And if I attempt to overload the copy constructor of Foo(uncomment Comment 1), a compile error occurred:

/tmp/ccuF5B5q.o: In function `__static_initialization_and_destruction_0(int, int)':
default.cpp:(.text+0x51): undefined reference to `Bar::f'
collect2: error: ld returned 1 exit status

My OS is ubuntu-14.04.5, and g++ version is 4.8.4.

I'm confused why this code works well?

Thanks in advance : p

Upvotes: 4

Views: 56

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

You did not provide a definition for Bar::f. As such, any odr-use of that object will result in a linker error. Your accepting a reference to it counts as that.

Either the implicit copy constructor does not count as odr-use or, more likely, because the implicit copy constructor is wholly invented by and owned by the compiler, it's more willing to optimise the copy away, so that your ODR violation is not diagnosed by the linker. Doesn't really matter either way.

Upvotes: 3

Related Questions