Why is the constructor instance not called when the object is returned by initializing the list?

I understand that when objects are returned by value from a function, their copy constructors are called. If the class has a remote instance-instance, a return by value will fail.

struct X { X(const X &) = delete; }; X f() { return X{}; } 

error: call to deleted constructor of 'X'

C ++ 11 gives us advanced initializers. And I read the SO post somewhere that this

 X f() { return {}; } 

coincides with

 X f() { return X{}; } 

So why doesn't the code below give me an error? It passes, and I can even call the main function:

 struct D { D(const D &) = delete; }; D f() { return {}; } int main() { f(); } 

Below is a demo. No errors reported. I find this strange because I believe that a copy constructor should be called. Can someone explain why the error is not indicated?

+7
c ++ c ++ 11
Mar 10 '13 at 22:06
source share
1 answer

And I read the SO post somewhere that this [...] matches [...]

They were wrong. They are similar, but not the same.

Using an extended list of commands, you can initialize the return value in place. If you create a temporary, then what you do creates a temporary and then copies it to the return value. Any compiler deserving its salt will be deprived of it, but the copy constructor should be available.

But since the braced-init list initializes the return value in place, you do not need access to the copy constructor.

From the standard, section 6.6.3, p2:

The return statement with the-init-list bandage initializes the object or link that will be returned from the function by initializing-initialization-list (8.5.4) from the specified list of initializers.

Note that "copy-list-initialization" is not like "copy-initialization"; it does not make any copies and therefore does not require an accessible copy constructor. The only difference between copy-list-initialization and direct-list initialization is that the former will throttle explicit constructors.

+12
Mar 10 '13 at 22:20
source share



All Articles