我想知道我是否可以使用以下内存分配方法?
I want to know is it okay if i will use following method of memory allocation?
我想知道我可以使用以下方法吗?没有语法错误和任何警告,但我想知道是否存在任何内存问题?
#include <iostream>
using namespace std;
class test {
int* x;
public:
test(int *n) { this->x = new int(*n); }
inline int get() { return *x; }
~test() { delete x; }
};
int main(void) {
while(1){
test a(new int(3));
cout << a.get() << endl;
}
return 0;
}
您违反了规则 3(自 c++11 起为 5)。这意味着既然你定义了析构函数,你应该定义 copy/move constructor/operation.
根据您的实施,copy/move constructor/operation 是错误的。当您复制对象时,它会浅拷贝您的指针并将其删除,因此您将进行双重删除。当你移动它时,你将删除一个你没有分配的指针。
奖励点:你的内联没用
您的代码中有 2 个问题:
你的class违反了rule of three/five/zero
创建时你正在泄漏内存a
在此代码中:
test a(new int(3));
您使用值 3 动态分配 int
并传递给 a
ctor,它使用值并创建它自己的动态分配 int
。之后这段内存就泄露了。如果你想将动态分配的数据传递给 class 使用智能指针:
class test {
std::unique_ptr<int> x;
public:
test(std::unique_ptr<int> n) : x( std::move( n ) ) { }
int get() const { return *x; }
};
int main()
{
x a( std::make_unique<int>( 3 ) ); // since c++14
x a( std::unique_ptr<int>( new int(3) ) ); // before c++14
...
}
并且您不需要显式实现 dtor,您没有违反规则,将动态分配的数据传递给 ctor 是安全的。
注意:我假设你使用 int
作为例子,你会明白动态分配一个 int
是没有用的,你应该按值存储它。
我想知道我可以使用以下方法吗?没有语法错误和任何警告,但我想知道是否存在任何内存问题?
#include <iostream>
using namespace std;
class test {
int* x;
public:
test(int *n) { this->x = new int(*n); }
inline int get() { return *x; }
~test() { delete x; }
};
int main(void) {
while(1){
test a(new int(3));
cout << a.get() << endl;
}
return 0;
}
您违反了规则 3(自 c++11 起为 5)。这意味着既然你定义了析构函数,你应该定义 copy/move constructor/operation.
根据您的实施,copy/move constructor/operation 是错误的。当您复制对象时,它会浅拷贝您的指针并将其删除,因此您将进行双重删除。当你移动它时,你将删除一个你没有分配的指针。
奖励点:你的内联没用
您的代码中有 2 个问题:
你的class违反了rule of three/five/zero
创建时你正在泄漏内存
a
在此代码中:
test a(new int(3));
您使用值 3 动态分配 int
并传递给 a
ctor,它使用值并创建它自己的动态分配 int
。之后这段内存就泄露了。如果你想将动态分配的数据传递给 class 使用智能指针:
class test {
std::unique_ptr<int> x;
public:
test(std::unique_ptr<int> n) : x( std::move( n ) ) { }
int get() const { return *x; }
};
int main()
{
x a( std::make_unique<int>( 3 ) ); // since c++14
x a( std::unique_ptr<int>( new int(3) ) ); // before c++14
...
}
并且您不需要显式实现 dtor,您没有违反规则,将动态分配的数据传递给 ctor 是安全的。
注意:我假设你使用 int
作为例子,你会明白动态分配一个 int
是没有用的,你应该按值存储它。