On Sep 25, 1:23 pm, "subramanian10...@yahoo.com, India"
<subramanian10...@yahoo.comwrote:
Consider the following program:
#include <iostream>
#include <string>
using namespace std;
class Test
{
public:
Test(const string & x = "") : str(x) { cout << "default ctor: " << str
<< endl; }
private:
Test(const Test & arg);
string str;
};
Test obj = string("test string");
int main()
{
return 0;
}
When I compile this program under g++, I get compilation error because
Test(const Test & arg);
is private.
Normal. Since it is private, you can only access it within the
class itself.
Note that if you write:
Test obj( std::string( "test string" ) ) ;
there should be no problem.
However consider the following program.
#include <iostream>
#include <string>
using namespace std;
class Test
{
static Test obj;
Test(const string & x = "") : str(x) { cout << "default ctor: " << str
<< endl; }
Test(const Test & arg);
string str;
};
Test Test::obj = string("test string");
int main()
{
return 0;
}
This program compiles fine under g++ and produces the output
default ctor: test string.
Right. The difference is that here, obj is a member of Test, so
it has a right to use private functions in its initializer.
The only difference is that the Test obj is static inside the Test
class in the second case.
Here also the copy ctor definition is not present.
Which means, formally, that your program has undefined behavior
in both cases. Practically, in the case of copy initialization
(initialization specified by means of the '=' token), the
compiler is explicitly allowed to elide the copy as an
optimization measure (even if the copy constructor has side
effects that affect the observable behavior of the program!),
and most compilers do, most of the time. But an accessible copy
constructor is still required to be present, and is formally
considered "used". Failure to provide a definition for a
function that is "used" is undefined behavior---in all of the
systems I know, however, it will cause a linker error if the
function is really used (as opposed to just formally "used"),
and the code will work if it is not actually used (as is the
case here).
However both programs compile fine under VC++2005 Express
Edition and produce the same result as above.
I do not understand.
VC++ has a bug.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34