TestObject getObject(){
TestObject a(5.0f);
return a;
}
int main(){
TestObject a = getObject();
}
Run Code Online (Sandbox Code Playgroud)
我是否正确地说,在C++中,返回的对象不会在返回时调用析构函数.是否在不运行析构函数的情况下删除了函数调用中占用的内存?
好的具体例子..
#include <iostream>
class Test{
public:
Test(){};
~Test(){std::cout << "Goodbye cruel world\n";}
};
Test getAnObject(){
Test a;
return a;
}
int main(){
Test a = getAnObject();
}
Run Code Online (Sandbox Code Playgroud)
如果我运行它,析构函数只运行一次(不适用于getAnObject()中的本地对象).我能否一直认为这种情况总是如此?
#include <iostream>
class Test{
public:
Test(){};
~Test(){std::cout << "Goodbye cruel world\n";}
};
Test getAnObject(){
Test a;
Test b;
int i = 0;
if (i){
return a;
}else{
return b;
}
}
int main(){
Test a = getAnObject(); …Run Code Online (Sandbox Code Playgroud) 我对如何做到这一点的最佳实践感到有些困惑.假设我有一个类,例如分配一些内存.我希望它像汽车一样自我毁灭,但也因为某种原因未知而将它放在矢量中.
#include <iostream>
#include <vector>
class Test {
public:
Test();
Test(int a);
virtual ~Test();
int counter;
Test * otherTest;
};
volatile int count = 0;
Test::Test(int a) {
count++;
counter = count;
std::cout << counter << "Got constructed!\n";
otherTest = new Test();
otherTest->counter = 999;
}
Test::Test() {
count++;
counter = count;
std::cout << counter << "Alloced got constructed!\n";
otherTest = NULL;
}
Test::~Test() {
if(otherTest != 0){
std::cout << otherTest->counter << " 1Got destructed" << counter << "\n";
otherTest->counter …Run Code Online (Sandbox Code Playgroud) c++ ×2