Pet*_*isu 6 c++ memory constructor allocation
如果我在已经构造的对象或结构上调用构造函数,它会分配新空间,还是只使用现有空间?那么第一个对象分配是否更加资源密集?像这样:
struct F {
int a,b,c,d;
F(int _a, int _b) {a = _a; b = _b};
void a(int _a, int _b) {a = _a; b = _b};
};
//first constructor call
F f = F(5, 6);
//second constructor call on an already constructed object
f = F(7, 8);
//third constructor call on an already constructed object
f(7, 8);
//is the constructor call more res. intesive, than the call to a function which does the same?
f.a(9, 0)
Run Code Online (Sandbox Code Playgroud)
构造函数是否调用了更多的资源intesive,而不是调用一个执行相同(void a(...)
)的函数?
当我在已经创建的对象上调用构造函数时,是否会调用析构函数?
首先,[c]
标记是不合适的,因为构造函数是仅限C++的特性.我假设你提供的代码片段实际上是C++而不是C. C++和C的一些奇怪的方言是不同的语言 ; 不要将你的问题标记为两者,因为你会得到不同的答案.
其次,构造函数定义是错误的.构造函数必须与类本身具有完全相同的名称. OP只是打错了.f()
应该如此F()
.是的,区分大小写在C++中很重要!我假设这是你对其余代码片段的意思.
在我解释其余代码的作用之前,您必须了解C++中的所有类(和结构)都有特殊的成员函数,如果您不提供这些函数,则由编译器自动生成.也就是说,您的代码段基本上与以下内容相同:
struct F
{
F(int _a, int _b) {a = _a; b = _b}; // constructor
~F() {} // destructor
F(const F& rhs) // copy constructor
: a(rhs.a)
, b(rhs.b)
, c(rhs.c)
, d(rhs.d)
{}
F& operator=(const F& a) // copy assignment operator
{
a = rhs.a;
b = rhs.b;
c = rhs.c;
d = rhs.d;
return *this;
}
void a(int _a, int _b) {a = _a; b = _b}; // one of your functions
int a;
int b;
int c;
int d;
};
Run Code Online (Sandbox Code Playgroud)
如果未定义复制构造函数,复制赋值运算符或析构函数,编译器将为您生成它们.此外,如果您不提供其他构造函数,编译器将生成默认构造函数.类没有默认构造函数,F
因为已经有一个(非复制)构造函数接受两个参数.
复制构造函数和复制赋值运算符的默认实现只是复制每个数据成员.
特殊成员函数存在的原因是因为C++概括了将基元类型复制到用户定义对象的概念.考虑一下:
int a = 42;
int b = 13;
b = a;
Run Code Online (Sandbox Code Playgroud)
对于像int
s 这样的原始类型,你可以像这样复制它的值.C++将复制语义概括为对象,因此您可以这样做:
F f(10, 20); // calls first constructor
F g(30, 40); // calls first constructor
g = f; // calls g's copy-assignment operator.
Run Code Online (Sandbox Code Playgroud)
现在您可以看到这对您的代码有何影响:
F f = F(5,6);
Run Code Online (Sandbox Code Playgroud)
上面的行构造一个临时F
对象,然后f
通过复制构造函数复制临时对象.F
然后破坏临时对象.
f = F(7,8);
Run Code Online (Sandbox Code Playgroud)
上面的行构造了另一个临时F
对象,然后f
通过复制赋值运算符分配临时对象.F
然后破坏临时对象.原始f
对象未被破坏.
f.a(9,0)
Run Code Online (Sandbox Code Playgroud)
上面的行是对被调用对象的正常函数调用f
.
对于你的代码片段,假设编译器没有优化临时值(实际上它们通常都是这样),那么调用函数a
是"资源消耗较少",因为在这种情况下不会产生临时值.但是,对于第一个构造函数调用,您可以这样做:
F f(5,6); // Constructor called; no temporaries are made
Run Code Online (Sandbox Code Playgroud)
了解构造函数的用途:它们用于创建对象.如果您已有对象,则无需调用构造函数.
正如我多次推荐的那样,请选一本好的C++书并阅读.特殊的成员函数及其所做的是C++的基础.