简体   繁体   English

在 c++ 中调用构造函数的正确方法是什么?

[英]what is the right way to call to constructor in c++?

    Communicator communicator = Communicator();

    Communicator communicator;

What is the difference between these 2 calls?这两个电话有什么区别?

The difference is in copy elision.区别在于复制省略。 Before C++17, in the line C++17之前,在行

Communicator communicator = Communicator();

a temporary Communicator object was created and then used to copy-construct communicator .创建了一个临时的Communicator object,然后用于复制构造communicator A compiler could optimize this out but it had to check that that copy or move constructor can be invoked (public, not deleted, not explicit ).编译器可以对此进行优化,但它必须检查是否可以调用该复制或移动构造函数(公共的、不删除的、不explicit的)。

Since C++17, copy elision rules have changes: "unmaterialized value passing" was introduced.自 C++17 以来,复制省略规则发生了变化:引入了“未实现的值传递”。 Now in that line no temporary object is created and no copy/move constructor is needed.现在在该行中没有创建临时 object 并且不需要复制/移动构造函数。

The following simple code will compile in C++17, but will fail to compile in C++11/14:以下简单代码将在 C++17 中编译,但在 C++11/14中编译失败

class Communicator {
public:
    Communicator() = default;
    Communicator(const Communicator&) = delete;
};

Communicator c = Communicator();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM