我经常看到人们使用C++创建对象
Thing myThing("asdf");
Run Code Online (Sandbox Code Playgroud)
而不是这个:
Thing myThing = Thing("asdf");
Run Code Online (Sandbox Code Playgroud)
这似乎有用(使用gcc),至少只要没有涉及模板.我现在的问题是,第一行是否正确,如果是这样,我应该使用它?
Jar*_*Par 141
这两条线实际上都是正确的,但却做了微妙的不同.
第一行通过调用格式的构造函数在堆栈上创建一个新对象Thing(const char*)
.
第二个有点复杂.它基本上做了以下
Thing
使用构造函数创建类型的对象Thing(const char*)
Thing
使用构造函数创建类型的对象Thing(const Thing&)
~Thing()
在步骤#1中创建的对象kni*_*ttl 30
我假设第二行你的意思是:
Thing *thing = new Thing("uiae");
Run Code Online (Sandbox Code Playgroud)
这将是创建新动态对象(动态绑定和多态性所必需)并将其地址存储到指针的标准方法.您的代码执行JaredPar描述的内容,即创建两个对象(一个传递一个const char*
,另一个传递一个const Thing&
),然后~Thing()
在第一个对象(const char*
一个)上调用析构函数().
相比之下,这:
Thing thing("uiae");
Run Code Online (Sandbox Code Playgroud)
创建一个静态对象,该对象在退出当前范围时自动销毁.
Dou*_*der 21
编译器可能会将第二种形式优化为第一种形式,但它不必.
#include <iostream>
class A
{
public:
A() { std::cerr << "Empty constructor" << std::endl; }
A(const A&) { std::cerr << "Copy constructor" << std::endl; }
A(const char* str) { std::cerr << "char constructor: " << str << std::endl; }
~A() { std::cerr << "destructor" << std::endl; }
};
void direct()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void assignment()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a = A(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void prove_copy_constructor_is_called()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
A b = a;
static_cast<void>(b); // avoid warnings about unused variables
}
int main()
{
direct();
assignment();
prove_copy_constructor_is_called();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
gcc 4.4的输出:
TEST: direct
char constructor: direct
destructor
TEST: assignment
char constructor: assignment
destructor
TEST: prove_copy_constructor_is_called
char constructor: prove_copy_constructor_is_called
Copy constructor
destructor
destructor
Run Code Online (Sandbox Code Playgroud)
Ste*_*oss 10
很简单,两行都在堆栈上创建对象,而不是像'new'那样在堆上创建.第二行实际上涉及对复制构造函数的第二次调用,因此应该避免(它还需要按照注释中的说明进行更正).你应该尽可能地将堆栈用于小对象,因为它更快,但是如果你的对象要比堆栈框架存活更长时间,那么它显然是错误的选择.
归档时间: |
|
查看次数: |
126006 次 |
最近记录: |