为什么不能将圆括号正确视为构造函数调用?

SHP*_*SHP 1 c++ constructor definition

我写了一个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";
      |               ^
Run Code Online (Sandbox Code Playgroud)

我替换代码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;
}
Run Code Online (Sandbox Code Playgroud)

cig*_*ien 5

这个说法:

Foo(x);
Run Code Online (Sandbox Code Playgroud)

不是函数调用或构造函数调用。这只是一个声明,表示x类型为Foo。declarator 周围的括号是可选的x,因此它等效于:

Foo x;
Run Code Online (Sandbox Code Playgroud)

这当然会产生错误,因为您已经有一个std::stringnamed x,并且您不能为同一范围内的多个实体提供相同的名称。


请注意表达式

Foo(x)
Run Code Online (Sandbox Code Playgroud)

与上面的语句不同(带有;)。这个表达可能意味着不同的东西,这取决于它所使用的上下文。


例如,这段代码:

Foo foo = Foo(x);
Run Code Online (Sandbox Code Playgroud)

完全没问题。这确实foo从表达式复制了一个名为 的变量的初始化Foo(x),它是Foo从参数构造的临时变量x。(这里不是特别重要,但是从 c++17 开始,右侧没有临时对象;对象只是在适当的位置构造)。