由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 问一个关于c++的很傻的问题,多谢
相关主题
关于singleton 的面试题问个题,没思路
问个C++题一道Coding面试题目
c++题Two C++ questions from Bloomberg on-site
A problem about Heap and Stack.one c++ questions
问几道老题Amazon电话面经
Char x[] = "abc"; 是在heap还是stack上? (转载)做题
C++ constructor problemGoogle电面被拒,郁闷中
请教一下怎么写unit test微软Fresh PHD SDE一般是什么级别? 61还是62
相关话题的讨论汇总
话题: heap话题: c++话题: test1话题: stack话题: instances
进入JobHunting版参与讨论
1 (共1页)
p********4
发帖数: 58
1
比如我写了一个class
class A
{
public:
void DoThis();
void DoThat();
}
当我使用它的时候,必须要在heap上产生一个instance吗?
int main()
{
A* test1 = new A(); //
A test2;// 这样也能正常工作,请问本质的区别在哪里,什么时候应该用哪个?我
的理解是一个是在heap上,一个是在stack上,如果不太大,就都可以,如果大,就应
该放在heap上。对吗?
}
另外A* test1 = new A(); 应该尽量用c++11,所以尽量写成如下? 可是我看leetcode网
上的很多答案,都用的老的c++ styple.
auto test1 = make_shared();
w**z
发帖数: 8232
2
这年头,为什么还要学c++?

【在 p********4 的大作中提到】
: 比如我写了一个class
: class A
: {
: public:
: void DoThis();
: void DoThat();
: }
: 当我使用它的时候,必须要在heap上产生一个instance吗?
: int main()
: {

g*********e
发帖数: 14401
3
你理解的对 如果只需在当前函数里用 就直接生成在stack省得忘记删除。如果要在别
的地方用就用heap。

【在 p********4 的大作中提到】
: 比如我写了一个class
: class A
: {
: public:
: void DoThis();
: void DoThat();
: }
: 当我使用它的时候,必须要在heap上产生一个instance吗?
: int main()
: {

m*******i
发帖数: 49
4
是的,一个在堆上,一个在栈上。一般情况下,随便哪个都可以。用new的时候,注意
要手动delete就行了。
建议用C++11,养成习惯。如果你面试的时候用了new,忘记delete,可能被面试官指出
。直接用make_shared,一上来就闪瞎面试官的32克拉眼,哈哈

【在 p********4 的大作中提到】
: 比如我写了一个class
: class A
: {
: public:
: void DoThis();
: void DoThat();
: }
: 当我使用它的时候,必须要在heap上产生一个instance吗?
: int main()
: {

t*****s
发帖数: 416
5
为了一辈子当码工

【在 w**z 的大作中提到】
: 这年头,为什么还要学c++?
x*******9
发帖数: 138
6
allocate on stack is faster than on heap, and it will take the advantage on
cache optimization
however, instance on stack is only available in current code block.
instance on heap is available everywhere if you get the pointer, but it's
slower and you have to deallocate it when you don't need them
a****r
发帖数: 87
7
like xunhuan119 said. instances allocated on heap have a global scope, and
instances allocated on stack have local scope. When the instances are out of
scope, their dtor will clean up the allocated memory. The global scoped
instances will never out of scope.
x*******9
发帖数: 138
8
@awbeer
Xunhuan19 not 119
:)
1 (共1页)
进入JobHunting版参与讨论
相关主题
微软Fresh PHD SDE一般是什么级别? 61还是62问几道老题
One C++ questionChar x[] = "abc"; 是在heap还是stack上? (转载)
gg面试题C++ constructor problem
C++ Q47: protected constructor (C39)请教一下怎么写unit test
关于singleton 的面试题问个题,没思路
问个C++题一道Coding面试题目
c++题Two C++ questions from Bloomberg on-site
A problem about Heap and Stack.one c++ questions
相关话题的讨论汇总
话题: heap话题: c++话题: test1话题: stack话题: instances