破坏局部变量的含义是什么:
void f()
{
int x=10;
}
Run Code Online (Sandbox Code Playgroud)
当该函数调用时,局部变量x的函数结束将是什么?
并为:
void f2()
{
int a=100;
int* b=&a;
}
Run Code Online (Sandbox Code Playgroud)
f2()结束那个局部变量int*b'的值是多少?b指针将是悬空指针(将有地址,但没有任何值)?
根据定义:当复制此类的对象时,复制指针成员,但不复制指向的缓冲区,导致两个对象指向同一个, 因此我们使用复制构造函数.
但在下面的类中没有复制构造函数,但它工作!为什么?为什么我不需要深度复制?
class Human
{
private:
int* aValue;
public:
Human(int* param)
{
aValue=param;
}
void ShowInfos()
{
cout<<"Human's info:"<<*aValue<<endl;
}
};
void JustAFunction(Human m)
{
m.ShowInfos();
}
int main()
{
int age = 10;
Human aHuman(&age);
aHuman.ShowInfos();
JustAFunction(aHuman);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
人类信息:10
人类信息:10
你能告诉我为什么不同编译器中该类引用成员的输出不同吗?
class B
{
int& aRef;
public:
B(int c):aRef(c){}
void Print()
{
cout<<aRef<<endl;
}
};
void f(int s)
{
int& lcRef=s;
cout<<lcRef<<endl;
}
int main()
{
int x=100;
B s(x);
s.Print(); //ms c++ output : 3323244, gcc output :100
f(x); //ms c++ output : 100, gcc output:100
return 0;
}
Run Code Online (Sandbox Code Playgroud)
函数的第二个问题参数与f(int s)B类初始化的构造函数表现相同的逻辑?
假设我有以下函数,它有一个类型为T的参数.该参数的生命周期是什么.
int* f()
{
int x=0;
int* ptr=&x;
return ptr; //i know this is undefined behavior.
}
Run Code Online (Sandbox Code Playgroud)
因此,在f()调用函数时,将运行本地expressios,并删除范围结束的指向值.但我的问题是关注以下功能
void f2(int* y)
{
}
int main()
{
int p=0;
f2(&p);
cout<<p<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这里,当我们调用f2()该参数时int* y会被删除?因此,如果删除的逻辑上指向的值将被删除,这是p,为什么我可以使用cout看到p的值相同?那么什么时候f2的论点会被删除?当函数的结束范围?或者是什么?
我的下面的类有未定义的行为?我认为它很明确,因为我通过引用传递构造函数参数.我对吗?
class C
{
int* elem;
public:
C(int s[]) :elem(s){}; // Array arguments passed by reference, so its well defined?
void Print()
{
cout << elem[1] << endl;
}
~C()
{
delete[] elem;
}
};
int main()
{
C x(new int[2]{1,3});
return 0;
}
Run Code Online (Sandbox Code Playgroud) 当我用另一个对象的副本初始化它时,为什么类对象的构造函数不起作用?
class Human
{
int No;
public:
Human(int arg):No(arg)
{
cout<<"constructor Works"<<endl;
}
};
int main()
{
Human a{10}; // constructor Works for object a
Human b{a}; //why b object's constructor dont work?
}
Run Code Online (Sandbox Code Playgroud)