小编lea*_*ude的帖子

'new' 和 'delete' 在 C++ 中被弃用了吗?

我偶然发现了一个涉及不同大小数组声明的测验。我想到的第一件事是我需要对new命令使用动态分配,如下所示:

while(T--) {
   int N;
   cin >> N;
   int *array = new int[N];
   // Do something with 'array'
   delete[] array;
}
Run Code Online (Sandbox Code Playgroud)

但是,我看到其中一种解决方案允许以下情况:

while(T--) {
    int N;
    cin >> N;
    int array[N];
    // Do something with 'array'
}
Run Code Online (Sandbox Code Playgroud)

经过一番研究,我读到 g++ 允许这样做,但它让我一直在思考,在哪些情况下有必要使用动态分配?还是编译器将其翻译为动态分配?

包括删除功能。但是请注意,这里的问题与内存泄漏无关。

c++ arrays dynamic-memory-allocation static-memory-allocation

68
推荐指数
4
解决办法
2万
查看次数

为什么这个 const auto 变量在 range-for 循环中为类的 const 成员函数编译?

我有以下类声明,根据我所了解的与 const 成员函数相关的知识,const 对象不能调用非常量成员函数。在 range-for 循环中,我们使用了“const auto animal”,它假设使用的是 const 对象,所以我认为在调用非常量成员函数 speak() 时,const 对象应该会给出编译错误,但它实际上编译,为什么?,也许我对 range-for 循环的真正工作方式没有明确的想法......谢谢!

#include <iostream>
#include <string>

class Animal {
protected:
     std::string name_;
     std::string speak_;
public:
    Animal(const std::string &name, const std::string &speak) : name_(name), speak_(speak){}
    const std::string &getName() const  { return name_;}
    std::string speak()  { return speak_;}
};

class Cat : public Animal{
public:
 Cat(const std::string &name) : Animal(name, "meow"){}
};

class Dog : public Animal{
public:
 Dog( const std::string &name) : Animal(name, "woof"){}
};

int main() { …
Run Code Online (Sandbox Code Playgroud)

c++ constants auto c++11 for-range

1
推荐指数
1
解决办法
137
查看次数

未检测到使用 -std=c++03 编译

我将这个简单的代码编译为 g++ main.cpp -o main -std=c++03

#include <vector>
int main(){
    std::vector<int> array;
    std::vector<int> array2 = { 9, 7, 5, 3, 1 };
}
Run Code Online (Sandbox Code Playgroud)

我收到以下编译错误:

main.cpp: 在函数 'int main()':
main.cpp:39:18: 错误:在 C++98 中,'array2' 必须由构造函数初始化,而不是由 '{...}'
std::vector数组 2 = { 9, 7, 5, 3, 1 };
                  ^~~~~~
main.cpp:39:43: 错误:无法将 '{9, 7, 5, 3, 1}' 从 '' 转换为 'std::vector'
std::vector array2 = { 9 , 7, 5, 3, 1 };

似乎即使我正在使用-std=c++03(初始化列表可用的地方)进行编译,但我仍在使用 C++98 标准。为什么会这样?

我知道此代码将使用更新的标准进行编译。

c++ c++-standard-library c++03

1
推荐指数
1
解决办法
165
查看次数