未调用复制构造函数进行复制初始化或优化?
如果复制构造函数设为私有
,那么在
情况1:没有错误的情况下,编译器不关心复制构造函数是否在类中定义。
情况 2: 错误,复制构造函数是私有的,当它成为公共
时,它会被忽略。
它是否直接优化副本而没有注意到构造函数是否被设为私有?
#include <string>
using std::string;
class T
{
string s;
T(const T &obj):s(obj.s){}
public:
T(const string &str):s(str){}
};
int main()
{
T a = ("Copy Initialization"); //Case: 1
T b = T("Copy Initialization"); //Case: 2
}
If copy constructor is made private
then in
Case 1: No error, the compiler doesn't care if the copy constructor was defined in class.
Case 2: Error, copy constructor is private and when it is made public
, it is elided.
Does it directly optimizes the copy without being noticing that if the constructor was made private
?
#include <string>
using std::string;
class T
{
string s;
T(const T &obj):s(obj.s){}
public:
T(const string &str):s(str){}
};
int main()
{
T a = ("Copy Initialization"); //Case: 1
T b = T("Copy Initialization"); //Case: 2
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
案例 2 在 N3225 中低于 12.8/31:
仅仅因为复制因子被省略并不意味着它没有被 ODR 使用。 3.2/2:
当然要注意,MSVC 不完全兼容 C++0x,因为 (a) C++0x 还不是标准,并且尚未最终确定; (b) MSVC 还没有实现最新的所有内容。但这个东西与 C++03 相比并没有实质性改变,所以我相当有信心这个解释仍然成立。
情况 1 也会属于这种情况,除了在我检查过的两个 C++03 编译器上它没有达到那么远,因为不可能从字符串文字到 T 的转换。我懒得去检查是否C++0x 中允许任何额外的转换序列,任何地方都可能有一个新子句:-)
对我来说,为什么 MSVC 允许情况 1 仍然是个谜,即使有一个公共复制构造函数。它允许在严格的 C++03 模式下使用吗?
Case 2 comes under 12.8/31 in N3225:
Just because the copy ctor is elided doesn't mean it isn't odr-used. 3.2/2:
Beware of course that MSVC is not fully C++0x-compliant, because (a) C++0x isn't a standard yet, and isn't finalized; and (b) MSVC hasn't implemented everything up to date anyway. But this stuff isn't substantially changed from C++03, so I'm fairly confident the explanation still holds.
Case 1 would come under this too, except that on the two C++03 compilers I've checked it doesn't get that far because there's no possible conversion from a string literal to T. I can't be bothered to check whether there are any additional conversion sequences allowed in C++0x, there could be a new clause anywhere :-)
It's still a mystery to me why MSVC allows case 1 ever, even with a public copy ctor. Does it allow it in strict C++03 mode?
T a = ("Copy Initialization");
应该给出错误,因为没有合适的从"const char [20]"
转换为"T"
的构造函数您的意思是
T a = std::string("Copy Initialization");< /代码>?
不,不能。编译器通常在代码优化阶段之前执行语法和语义分析。
T a = ("Copy Initialization");
should give an error because there's no suitable constructor to convert from"const char [20]"
to"T"
Did you mean
T a = std::string("Copy Initialization");
?No it can't. Compilers usually perform syntactic and semantic analysis prior to the code optimization phase.