gpt4 book ai didi

C++ 为什么在栈中构造完对象后立即调用析构函数?

转载 作者:搜寻专家 更新时间:2023-10-31 00:11:27 28 4
gpt4 key购买 nike

我有两个单元测试。在第一个中,我在堆栈中创建对象 myMovie。创建对象后立即调用析构函数。这会导致单元测试失败,因为当 myMovie 超出范围时,将再次调用析构函数。这会导致访问冲突。

但是,如果我在堆中创建对象,一切正常。为什么在栈中构造完对象后立即调用析构函数?

第一个像这样:

TEST_METHOD(constructingMovieWithParametersStack)
{
_CrtMemState s1, s2, s3;
_CrtMemCheckpoint(&s1);
{
Movie myMovie = Movie("firstName", "lastName", "title");
// Why is the destructor is called here???

string expectedDirectorFirst = "firstName";
string expectedDirectorLast = "lastName";
string expectedTitle = "title";
wchar_t* message = L"movie title wasn't set correctly";
Assert::AreEqual(expectedTitle, myMovie.getTitle(), message, LINE_INFO());
}
_CrtMemCheckpoint(&s2);
wchar_t* leakMessage = L"there is a leak";
bool isThereALeak = _CrtMemDifference(&s3, &s1, &s2);
Assert::IsFalse(isThereALeak, leakMessage, LINE_INFO());
}

第二个单元测试是这样的:

TEST_METHOD(constructingMovieWithParametersHeap)
{
_CrtMemState s1, s2, s3;
_CrtMemCheckpoint(&s1);
{
Movie* myMovie = new Movie("firstName", "lastName", "title");

string expectedDirectorFirst = "firstName";
string expectedDirectorLast = "lastName";
string expectedTitle = "title";
wchar_t* message = L"movie title wasn't set correctly";
Assert::AreEqual(expectedTitle, myMovie->getTitle(), message, LINE_INFO());
delete myMovie;
}
_CrtMemCheckpoint(&s2);
wchar_t* leakMessage = L"there is a leak";
bool isThereALeak = _CrtMemDifference(&s3, &s1, &s2);
Assert::IsFalse(isThereALeak, leakMessage, LINE_INFO());
}

这是电影类:

#include "Movie.h"

using namespace std;

Movie::Movie()
{
this->director = new Person();
this->title = "";
this->mediaType = 'D'; // for DVD
}

Movie::Movie(string firstName, string lastName, string title)
{
this->director = new Person();
this->director->setFirstName(firstName);
this->director->setLastName(lastName);
this->title = title;
this->mediaType = 'D'; // for DVD
}

Movie::~Movie()
{
delete director;
}

string Movie::getTitle()
{
return title;
}

最佳答案

Movie myMovie = Movie("firstName", "lastName", "title");
// Why is the destructor is called here???

这里创建了一个临时对象并用于复制初始化myMovie,然后销毁临时对象。

你是说

Movie myMovie("firstName", "lastName", "title");

关于C++ 为什么在栈中构造完对象后立即调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33976902/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com