通过值或引用调用时未调用构造函数/析构函数.不管怎样
Constructor/Destructor function not being called while calling by value or reference. Any way around it?
由于c++的一个特性,我遇到了麻烦。在处理了动态内存分配之后,由于明显的原因,我总是清除堆(空闲存储)。我用析构函数来实现。有时,使用构造函数来分配内存。但在从另一个函数调用对象(按值调用)之后,只有析构函数才能工作。我知道在很多情况下这是一个很好的功能。但是,在处理许多独立功能时,这很烦人。有办法绕过它吗,伙计们?或者,我应该只使用成员函数来分配和清除内存吗?
一个例子:
#include <iostream>
using namespace std;
class test{
int *a;
public:
test(int x) {a=new int;
*a=x;}
int geta(){return *a;}
~test(){delete a;}
};
int apow2(test t)
{
return ((t.geta())*(t.geta()));
}
int main()
{
test tst(10);
cout<<"nA^2="<<apow2(tst);
//at this point, memory reference to 'a' doesn't exist
cout<<"n"<<tst.geta();
return 0;
}
您遇到了麻烦,因为您没有为类test
实现复制构造函数和副本赋值运算符:您没有遵守三规则。
但是,好消息!你不需要。你可以通过存储int
而不是int*
:来避免所有的混乱
class test
{
int a;
public:
test(int x)
: a{x}
{}
};
就是这样!没有动态分配,没有内存管理,什么都没有。只有test
,还有一个int
,它可以精确地存活test
的寿命。完美的
如果你因为问题中没有说明的原因而需要动态分配(哇),那么你应该使用智能指针来为你管理它的生命周期:
class test
{
std::unique_ptr<int> a;
public:
test(int x)
: a{new int(x)}
{}
int geta() { return *a; }
};
就是这样!没有内存管理,什么都没有。只有test
,还有一个int*
,它的指针可以精确地存活test
的生命周期。完美的
相关文章:
- 在c++中使用向量时,如何调用构造函数和析构函数
- C++:考虑但不调用构造函数的特殊性
- 对象实例化调用构造函数的次数太多
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- C ++:通过大括号调用构造函数?
- 不能调用构造函数
- 赋值 boost::intrusive_ptr 而不调用构造函数?
- 在模板化类的构造函数中调用构造函数
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 我不明白在这个例子中什么时候调用构造函数
- 调用c++构造函数的不同方法
- 调用构造函数与将内联常量定义为默认参数
- 如何通过 Rust FFI 调用C++构造函数?
- "new"运算符是否总是调用构造函数?
- 无法调用构造函数
- 使用 "()" 调用构造函数不同于"{}"
- 确定是调用构造函数还是强制转换运算符的因素