在C ++代码中复制构造函数,指针,真或假问题

时间:2020-12-05 20:34:48

I'm knew to C++ so if anyone could help me out with these TorF questions it would be great.

我知道C ++,所以如果有人能帮我解决这些TorF问题,那就太好了。

True or False: Using C++, the copy constructor for a class is only used when passing by value to a function input.

对错:使用C ++,只有在将值传递给函数输入时才使用类的复制构造函数。

True or False: The following C++ function madeA() is a valid function implementation.

对错:以下C ++函数madeA()是一个有效的函数实现。

ClassA{
public:
    int x;
    char *y;
};
void madeA(const A &t_a){
    t_a.x = 1;
    t_a.y = 0;
}

True or False: The following C++ code segments are equivalent.

对错:以下C ++代码段是等效的。

void cmax(int a, int b, int *max){
    if(a>b) *ax = a;
    *max = b;
}

using namespace std;

void main(){
    int *max = new int;
    cmax(20, 5, max);
    cout<< *ax << endl;
}

next code:

void cmax(int a, int b, int &max){
    if(a>b) max = a;
    max = b;
}

void(){
    int max;
    cmax(20, 5, ax);
    std::cout <<max<<std::endl;
 }

1 个解决方案

#1


1  

First: False.
The copy constructor might be invoked anytime a copy is needed.
Simple example: return by value

第一:错。可以在需要副本时随时调用复制构造函数。简单示例:按值返回

Second: False.
You are modifying contents of a reference to const argument. It shouldn't compile and even if you use some pointer hackery it would result in Undefined Behavior.

第二:错。您正在修改对const参数的引用的内容。它不应该编译,即使你使用一些指针hackery,它也会导致Undefined Behavior。

Third: False.
First has a memory leak second doesn't.
The second code snippet won't even compile.

第三:错。第一个有内存泄漏第二个没有。第二个代码片段甚至不会编译。

#1


1  

First: False.
The copy constructor might be invoked anytime a copy is needed.
Simple example: return by value

第一:错。可以在需要副本时随时调用复制构造函数。简单示例:按值返回

Second: False.
You are modifying contents of a reference to const argument. It shouldn't compile and even if you use some pointer hackery it would result in Undefined Behavior.

第二:错。您正在修改对const参数的引用的内容。它不应该编译,即使你使用一些指针hackery,它也会导致Undefined Behavior。

Third: False.
First has a memory leak second doesn't.
The second code snippet won't even compile.

第三:错。第一个有内存泄漏第二个没有。第二个代码片段甚至不会编译。