【发布时间】:2020-09-14 14:07:34
【问题描述】:
我写了一个move来模仿std::move,并尝试使用一个新的结构Foo来测试它。但是,发生了一些错误。
.\main.cpp: In function 'int main()':
.\main.cpp:46:7: error: conflicting declaration 'Foo x'
46 | Foo(x);
| ^
.\main.cpp:43:15: note: previous declaration as 'std::string x'
43 | std::string x = "123";
| ^
我将代码Foo(x) 替换为Foo foo = Foo(x),然后一切正常。
我正在使用MinGW32 g++ 9.2.0,使用命令g++ main.cpp -std=c++14进行编译
详情请看下面的代码:
#include <iostream>
template <class T>
struct Remove_Reference {
typedef T type;
};
template <class T>
struct Remove_Reference<T&> {
typedef T type;
};
template <class T>
struct Remove_Reference<T&&> {
typedef T type;
};
template <typename T>
constexpr typename Remove_Reference<T>::type&& move(T&& x) noexcept {
return static_cast<typename Remove_Reference<T>::type&&>(x);
}
struct Foo {
Foo() {}
Foo(std::string&& foo) : val(foo) {
std::cout << "rvalue reference initialize" << std::endl;
}
Foo(const std::string& foo) : val(::move(foo)) {
std::cout << "const lvalue reference initialize" << std::endl;
}
std::string val;
};
void call(std::string&& x) {
std::cout << "rvalue reference: " << x << std::endl;
}
void call(const std::string& x) {
std::cout << "const lvalue reference: " << x << std::endl;
}
int main() {
std::string x = "123";
Foo{x};
// Foo(x);
Foo{::move(x)};
Foo(::move(x));
call(x);
call(::move(x));
return 0;
}
【问题讨论】:
-
您希望
Foo{x};应该做什么?创建一个匿名临时? -
@DanielLangr 是的
-
对不起,在我之前的评论中应该是
Foo(x);。这里也是标准的相关部分:eel.is/c++draft/stmt.ambig。不管怎样,你可以改写Foo(x).val;。 -
你可能想查找“最令人头疼的解析”。
-
@n.'pronouns'm。查找是一个好主意,但是
Foo(x);没有令人烦恼的解析。它不能是函数声明。
标签: c++ constructor definition