c++ - 初始化:当 value 类型为 T 时,T x(value) 与 T x = value

标签 c++ initialization

T x(value) 通常是更好的选择,因为它将直接用 value 初始化 x,而 T x = value 可能会根据值的类型创建临时值。 不过,在 value 类型为 T 的特殊情况下,我的猜测是表达式 T x = value 将始终导致一次复制构造函数调用。我说得对吗?

我问这个问题是因为我开始认为第一个语法太丑陋且难以理解,特别是当值是函数调用的结果时。 例如:

  • const std::string path(attributes.data(pathAttrib));
  • const std::string path = attribute.data(pathAttrib);

最佳答案

T x(value) is usually the better choice because it will directly initialize x with value, whereas T x = value might create a temporary depending on the type of value.

你几乎是对的,更好的选择是最清晰的语法。以下是两者的区别:

The form of initialization (using parentheses or =) is generally insignificant, but does matter when the entity being initialized has a class type... [8.5/11]

struct A {
  A(int) {}
};
struct B {
  explicit B(int) {}
};

int main() {
  { A obj (42); } // succeeds
  { A obj = 42; } // succeeds

  { B obj (42); } // succeeds
  { B obj = 42; } // fails
}

需要隐式转换,所以像vector<int> v = 3;这样的东西失败了,但是无论如何,这看起来都是错误的,对吧?任何拷贝都可能elided 。我不记得发现这是我编写的任何内容的瓶颈,而且我很久以前就不再担心它:只需使用最清晰的语法即可。


In the special case where value is of type T though, my guess is that the expression T x = value will always result in exactly one copy constructor call. Am I correct?

不,你不能保证复制构造函数总是被调用,但它必须是可访问的。例如,在上面的具体情况下 value作为函数的返回值,标准明确允许删除这些拷贝。

关于c++ - 初始化:当 value 类型为 T 时,T x(value) 与 T x = value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1816547/

相关文章:

c++ - 为什么调用主函数应该是未定义的行为 (UB)

c++ - 使用优先级队列初始化 vector

c++ - 成员函数的相互返回类型(C++)

c++ - "int* ptr = int()"值初始化如何不非法?

java - 始终通过上下文在 Spring 服务中注入(inject)一些字段

python - 使用唯一集初始化 python 列表

Ruby - Thor 首先执行特定任务

c++ - 将包含指针的数据插入 vector

c++ - 迭代 std::list<boost::variant>

c++ - 如何在 GPU 而不是 CPU 上运行 qt 应用程序