这是一个小代码片段:
class A
{
public:
A(int value) : value_(value)
{
cout <<"Regular constructor" <<endl;
}
A(const A& other) : value_(other.value_)
{
cout <<"Copy constructor" <<endl;
}
private:
int value_;
};
int main()
{
A a = A(5);
}
Run Code Online (Sandbox Code Playgroud)
我假设输出将是"常规构造函数"(对于RHS),后面是LHS的"复制构造函数".所以我避免使用这种风格并始终将类的变量声明为A a(5);.但令我惊讶的是上面的代码从未调用过复制构造函数(Visual C++ 2008)
有没有人知道这种行为是由编译器优化,还是C++的一些记录(和可移植)功能引起的?谢谢.
struct my
{
my(){ std::cout<<"Default";}
my(const my& m){ std::cout<<"Copy";}
~my(){ std::cout<<"Destructor";}
};
int main()
{
my m(); //1
my n(my()); //2
}
Run Code Online (Sandbox Code Playgroud)
预期产量:
1 ) Default
2 ) Copy
Run Code Online (Sandbox Code Playgroud)
实际产量:
我对构造函数调用机制的理解有什么问题?
Note 为简洁起见,我省略了头文件.
我遇到了一个代码片段,并认为它会调用copy-constructor,但相比之下,它只是调用了普通的构造函数.下面是代码
#include <iostream>
using namespace std;
class B
{
public:
B(const char* str = "\0")
{
cout << "Constructor called" << endl;
}
B(const B &b)
{
cout << "Copy constructor called" << endl;
}
};
int main()
{
B ob = "copy me";
return 0;
}
Run Code Online (Sandbox Code Playgroud)