lundi 28 septembre 2015

C++ confusion about accessibility of special member function

Consider a statement like following:

Test t=Test();

AFAIK it value initializes a temporary & copy initializes it.

Now consider following program:

#include <iostream>
struct Test
{
    Test(const Test& s)
    {
        std::cout<<"Copy constructor\n";
        m=s.m;
    }
    Test(Test&& s)=delete;
    Test()=default;
    int m;
};
int main()
{
    Test t=Test();
    std::cout<<t.m<<'\n';
}

g++ gives me following error:

16  14  [Error] use of deleted function 'Test::Test(Test&&)'

9   2   [Error] declared here

So, statement like Test t=Test(); calls copy constructor in C++98 & C++03 & calls move constructor since C++11. right? But If I define move constructor explicitly in above program like following:

#include <iostream>
struct Test
{
    Test(const Test& s)
    {
        std::cout<<"Copy constructor\n";
        m=s.m;
    }
    Test()=default;
    Test(Test&& s) { std::cout<<"Move constructor\n"; m = s.m; }
    int m;
};
int main()
{
    Test t=Test();
    std::cout<<t.m<<'\n';
}

But when I run the program move constructor isn't called. So, it looks like C++ compiler perform copy elision.

My question is that: If an implementation is permitted to eliminate the need to call move constructor then why is it not accepting the code when the move constructor is deleted? After all, its not calling it. Its like a spoiled kid who first irritatingly asks for a specific toy, and when you give him one, the specific one, he throws it away, behind your back.

Correct me If I am wrong in my understanding. I don't know much about move semantics feature of C++11. I hope that I have represented my question clearly this time & it has enough details.

Aucun commentaire:

Enregistrer un commentaire