gpt4 book ai didi

c++ - 编译时复制构造函数/复制赋值和普通函数调用优化有什么区别吗?

转载 作者:行者123 更新时间:2023-11-28 02:04:49 24 4
gpt4 key购买 nike

我在测试一个小例子时遇到了一个有趣的编译错误:

#include <iostream>

using namespace std;

class A
{
public:
A() { cout <<"A created." <<endl; }
A(A& a) { cout <<"A created by copy constructor." <<endl; }
~A() { cout <<"A destoryed." <<endl; }
};

A CreateObject()
{
A obj;
return obj;
}

int main()
{
A a;
A b;

b= CreateObject();

return 0;
}

它很简单,可能根本没有任何问题。但是,它在编译时提示:

copy_constructor.cpp: In function ‘int main()’:
copy_constructor.cpp:23: error: no matching function for call to ‘A::A(A)’
copy_constructor.cpp:9: note: candidates are: A::A(A&)

程序似乎在编译“b=CreateObject();”时试图调用复制构造函数但是没有匹配的复制构造函数。这不应该发生,因为它只是一个赋值语句,构造函数和普通函数在编译优化方面有什么区别吗?

最佳答案

A(A& a) { cout <<"A created by copy constructor." <<endl; }
...
b = CreateObject();

根据 C++03 标准,这是无效的。

在 C++03 中,b = CreateObject() 实际上可能扩展为 b = A(CreateObject());。这仅在后来的 C++ 版本中被“修复”,现在禁止创建临时拷贝。

CreateObject() 返回一个 r-hand 值,该值只能由具有 A(const A& a) 签名的复制构造函数使用。如果没有 const 修饰符,它仅适用于左手值。

例如b = a 对于该签名和扩展仍然有效,因为您可以在构造函数中修改 a


这仍然是可复制的,将 clang++ 设置为 C++98 标准:http://coliru.stacked-crooked.com/a/50c25c469420ab0f

旧版本的 Visual-C++ 表现出 OP 显示的精确错误。

g++ 无法正确验证这一点,即使在明确指定 C++98 时也是如此。

另见 https://stackoverflow.com/a/13898867/2879325

关于c++ - 编译时复制构造函数/复制赋值和普通函数调用优化有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37944050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com