没有匹配的复制构造函数的错误

时间:2017-10-05 16:48:33

标签: c++ c++11

使用g ++ 5.7编译时出现以下错误,当我删除显式减速时,它会编译而没有警告。但我想知道原因。

编译错误消息:

move_semantics.cpp: In function ‘MyString hello_world_return_copy()’:
move_semantics.cpp:44:9: error: no matching function for call to ‘MyString::MyString(MyString&)’
  return s;
         ^
move_semantics.cpp: In function ‘MyString hello_world_return_move()’:
move_semantics.cpp:51:20: error: no matching function for call to ‘MyString::MyString(std::remove_reference<MyString&>::type)’
  return std::move(s);
                    ^
move_semantics.cpp: In function ‘MyString hello_world_return_statc()’:
move_semantics.cpp:57:33: error: no matching function for call to ‘MyString::MyString(MyString&)’
  return static_cast<MyString&>(s);
                                 ^
move_semantics.cpp: In function ‘int main()’:
move_semantics.cpp:67:42: error: no matching function for call to ‘MyString::MyString(MyString)’
  MyString temp = hello_world_return_copy();

源:

#include <string>
#include <iostream>

struct MyString {

    explicit MyString(const char* input) {
        std::cout << "Constructor called" << std::endl;
        _str = std::string(input);
    }

    explicit MyString(const MyString& other) {
        std::cout << "Copy constructor called" << std::endl;
        _str = other._str;
    }

    explicit MyString(MyString& other) {
        std::cout << "Copy constructor called" << std::endl;
        _str = other._str;
    }

    ~MyString() {
        std::cout << "destructor called" << std::endl;
    }   

private:
    std::string _str;
};

MyString hello_world_return_copy()
{
    MyString s("hello world!");
    return s;
}

MyString hello_world_return_move()
{
    MyString s("hello world!");
    // move takes an lvalue as argument and returns an rvalue
    return std::move(s);
}

int main() {
    MyString temp = hello_world_return_copy();
}

我正在尝试实验并学习更多关于移动语义,rvalues等等。奇怪的是编译器抱怨没有MyString::MyString(MyString&)函数,尽管我确实有。{/ p>

0 个答案:

没有答案