[英]Destructor in struct and class in c++
我應該為此結構創建析構函數嗎? 還是有任何隱式析構函數&&在超出范圍時會被破壞?
在這里,myLogStructure和mySubject都是結構類型。
#include "stdafx.h"
#ifndef MyLogStruct_H
#define MyLogStruct_H
#include <string>
#include<windows.h>
using namespace std;
struct mySubject
{
string Security_ID;
string Account_Name;
string Account_Domain;
string Logon_ID;
};
struct myLogStructure
{
string message;
bool isAvailableMySubject;
mySubject mySubject1;
};
#endif
我應該為此實現析構函數嗎? 還是超出范圍會被破壞?
這里MyLogStructure和MySubject都是類類型。 請注意我在此類中使用了指針的一件事。
#include "stdafx.h"
#ifndef MyLogStructure_H
#define MyLogStructure_H
#include <string>
#include "MySubject.h"
using namespace std;
class MyLogStructure
{
public:
MyLogStructure(LPWSTR providerMessageString1, int version1);
~MyLogStructure(void);
const wchar_t* message;
LPWSTR providerMessageString;
int version;
bool isAvailableMySubject;
MySubject*mySubject;
};
#endif
class MySubject
{
public:
MySubject(const wchar_t* Security_ID1, const wchar_t* Account_Name1, const wchar_t* Account_Domain1, const wchar_t* Logon_ID1);
~MySubject(void);
const wchar_t* Security_ID;
const wchar_t* Account_Name;
const wchar_t* Account_Domain;
const wchar_t* Logon_ID;
};
是否需要析構函數並不取決於您使用struct
還是class
。 決定因素是struct
/ class
是否已獲取必須在對象的生命周期結束時顯式釋放的資源。 如果問題的答案是肯定的,那么您需要實現一個析構函數。 否則,您無需實現它。
對於第一組struct
,最好讓編譯器實現析構函數。 析構函數中無事可做。
如果實施它們,它們將是:
~mySubject() {}
和
~myLogStructure() {}
您可能需要在第二組類中實現析構函數,具體取決於是否需要釋放任何資源。
由於您有指向w_char
指針來存儲該數據,因此您很可能需要實現析構函數,並釋放在對象生存期內獲取的內存。
您不需要為mySubject
或myLogStructure
提供自己的析構函數,因為編譯器生成的析構函數可以正常工作(它們將調用std::string
成員的析構函數)。
如果這些類管理內存,則確實需要為MyLogStructure
和MySubject
提供析構函數,考慮指針類型的成員似乎是這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.