2

This question refers only to pre C++11. Consider the following seemingly broken code:

struct X
{
    X(){} // default user-provided constructor
private:
    X(const X&){}
};

int main()
{
    X x = X();
}

Live on Coliru

According to cppreference.com in pre C++11 the default ctor will be called:

The effects of value initialization are:

1) if T is a class type with at least one user-provided constructor of any kind, the default constructor is called;

...

This seem to imply that the copy ctor doesn't necessarily need to be accessible. Is this correct or not? The code above does not compile, so it seems that a copy ctor must be accessible.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • 1
    Apparently I misread cppreference.com in my [previous answer](http://stackoverflow.com/a/34602774/65863). #1 you quote above refers to the `X()` proportion of the `X x = X();` expression. That is default-constructing a temp object. The `x = ...` portion then copy-constructs `x` using the temp object as input. – Remy Lebeau Jan 05 '16 at 01:53
  • C++98 doesn't have a notion of "value initialization". That was added in C++03. – Kerrek SB Jan 05 '16 at 01:54
  • @KerrekSB So basically there is no way to "trick" the compiler in simulating `X x{};` in C++98/03. In other words, the code above compiles in C++11 if we do `X x{};`, and it seems there is no way to achieve the same effect with C++98/03. Of course `X x();` won't do it, as [we all know](https://en.wikipedia.org/wiki/Most_vexing_parse). – vsoftco Jan 05 '16 at 01:58
  • @vsoftco: Well, if it's so important, you can write a wrapper: `template struct VI { VI() : t() {} T t; };`... – Kerrek SB Jan 05 '16 at 02:21

1 Answers1

5

Value initialization doesn't require it, but you need an accessible copy constructor to do this:

X x = X();

That's copy initialization, which requires an accessible copy constructor. Even though it will not call that copy constructor, it still needs to exist.

C++17 might be the first version where that need will be lifted.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • Ohh ok, yes, value initialization is done on the temporary. And yes, for copy initialization, we need an accessible copy ctor, even if copy elision is performed. – vsoftco Jan 05 '16 at 01:53